[英]MVC @Html.Dropdownlistfor Not Returning the Correct Values From List
[英]Way to return a list from DAC Layer without using IEnumerable<SelectListItem> of System.Web.Mvc at that layer to bind MVC @Html.DropdownListFor()
是否有任何方法可以从DAC层返回列表,而无需使用DAC层的System.Web.Mvc的IEnumerable来绑定MVC @ Html.DropdownListFor()以获得mvc中的强类型视图
简单-使用视图模型并在控制器中填充选择列表
模型
public class CreateUserViewModel
{
public int RoleId { get; set;}
public IEnumerable<SelectListItem> RolesSelectList { get; set; }
}
调节器
public ActionResult Create()
{
CreateUserViewModel model = new CreateUserViewModel();
model.RolesSelectList = DAC.GetRoles().Select(role => new SelectListItem() { Text = Role.Name, Value = Role.RoleId.ToString() });
return View(model);
}
视图
@model CreateUserViewModel
@Html.DropDownListFor(model => model.RoleId, Model.RolesSelectList);
为什么不能只将列表绑定到视图本身? 如果您的模型包含IEnumerable类型的名为Roles的属性,则在您的视图中可以执行以下操作:
@Html.DropDownListFor(m => m.RoleId, new SelectList(Model.Roles, "YourDataValueFieldName", "YourDataTextFieldName"))
换句话说,您可以随模型传递任何满足IEnumerable接口的对象,并将其绑定到视图本身的SelectList上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.