我想在地区 Controller 中使用状态 Controller 列表。有没有更好的主意。 我已经尝试过一个有效的
我通过使用构造函数注入(inject)将这段代码放在区域 Controller 中。
在这种情况下,需要将整个代码放在分区 Controller 中。 有什么办法可以减少代码。有更好的方法吗?
#region StateDropDown
public List<SelectListItem> StateDropDown()
{
List<SelectListItem> selectListItem = new List<SelectListItem>();
List<StateViewModel> stateList = Mapper.Map<List<State>, List<StateViewModel>>(_stateBusiness.GetStateForSelectList());
if (stateList != null)
foreach (StateViewModel state in stateList)
{
selectListItem.Add(new SelectListItem
{
Text = state.Description,
Value = state.Code.ToString(),
Selected = false
});
}
return selectListItem;
}
#endregion StateDropDown
最佳答案
这就是发明“可重用性”一词的原因。将代码放在另一个文件中,并从您想要的任意数量的 Controller 调用它,如下面的代码。
//StateBusiness.cs
public class StateBusiness
{
public List<SelectListItem> GetStatesForDropdown()
{
//your logic here
return new List<SelectListItem>();
}
}
//StateController.cs
public class StateController : Controller
{
var state = new StateBusiness();
public ActionResult Index()
{
//call your code here
var states = state.GetStatesForDropdown();
//and do whatever you want
ViewBag.states = states;
return View();
}
}
//DistrictController.cs
public class DistrictController : Controller
{
var state = new StateBusiness();
public ActionResult Index()
{
//call it from here just the same
var states = state.GetStatesForDropdown();
ViewBag.states = states;
return View();
}
}
关于c# - C# MVC 中 Controller 到 Controller 的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548374/