Populating a razor dropdownlist from a List<object> in MVC
我有一个模型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class DbUserRole { public int UserRoleId { get; set; } public string UserRole { get; set; } } public class DbUserRoles { public List<DbUserRole> GetRoles() { BugnetReports RoleDropDown = new BugnetReports(); List<DbUserRole> Roles = new List<DbUserRole>(); DataSet table = RoleDropDown.userRoleDropDown(); foreach (DataRow item in table.Tables[0].Rows) { DbUserRole ur = new DbUserRole(); ur.UserRole = Convert.ToString(item["UserRoleName"]); ur.UserRoleId = Convert.ToInt32(item["UserRoleID"]); Roles.Add(ur); } return Roles; } } |
这里是加载视图的控制器:
1 2 3 4 5 6 7 8 | // // GET: /Admin/AddNewUser public ActionResult AddNewUser() { DbUserRoles Roles = new DbUserRoles(); return View(Roles.GetRoles()); } |
我可以使用
1 2 3 4 5 6 7 8 9 10 11 | @foreach (var item in Model) { <tr> <td> @item.UserRoleId </td> <td> @item.UserRole </td> </tr> } |
但是如何用传递的模型填充DropDownList,我已经尝试过了
但我运气不好。
您可以将业务逻辑分离为一个视图模型,这样您的视图就有了更清晰的分离。
首先创建一个viewModel来存储用户将选择的ID以及将出现在
ViewModel:
1 2 3 4 5 6 7 | public class UserRoleViewModel { // Display Attribute will appear in the Html.LabelFor [Display(Name ="User Role")] public int SelectedUserRoleId { get; set; } public IEnumerable<SelectListItem> UserRoles { get; set; } } |
参考文献:
DisplayAttribute
在控制器内部,创建一个方法来获取您的
控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | private IEnumerable<SelectListItem> GetRoles() { var dbUserRoles = new DbUserRoles(); var roles = dbUserRoles .GetRoles() .Select(x => new SelectListItem { Value = x.UserRoleId.ToString(), Text = x.UserRole }); return new SelectList(roles,"Value","Text"); } public ActionResult AddNewUser() { var model = new UserRoleViewModel { UserRoles = GetRoles() }; return View(model); } |
参考文献:
SelectListItem SelectList Constructor (IEnumerable, String, String)
现在创建了视图模型,表示逻辑就简化了
观点:
1 2 3 4 | @model UserRoleViewModel @Html.LabelFor(m => m.SelectedUserRoleId) @Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles) |
参考文献:
LabelExtensions.LabelFor SelectExtensions.DropDownListFor
这将产生:
1 2 3 4 5 6 | <label for="SelectedUserRoleId">User Role</label> <select id="SelectedUserRoleId" name="SelectedUserRoleId"> <option value="1">First Role</option> <option value="2">Second Role</option> <option value="3">Etc...</option> </select> |
1 2 3 4 5 6 | @Html.DropDownList("ddl",Model.Select(item => new SelectListItem { Value = item.RecordID.ToString(), Text = item.Name.ToString(), Selected ="select" == item.RecordID.ToString() })) |
一种可能是;
1 2 3 4 5 6 7 8 9 | <select name="listbox" id="listbox"> @foreach (var item in Model) { <option value="@item.UserRoleId"> @item.UserRole </option> } </select> |
接近于:
1 2 3 |
您需要一个SelectList来填充DropDownListfor。对于所需的任何HTML属性,可以添加:
1 |
您可以让您的模型包含一个
填写选择列表,然后在视图中使用:
1 | @Html.DropDownListFor(x => x.SelectedUserRoleId, x.UserRole) |
你应该没事的。
另请参见http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx。
你对
MVC3 DropDownListfor-一个简单的例子?
有了这些,您只告诉它在哪里存储数据,而不是从哪里加载列表。
1 2 3 4 5 6 7 8 9 10 11 12 | @{ List<CategoryModel> CategoryList = CategoryModel.GetCategoryList(UserID); IEnumerable<SelectListItem> CategorySelectList = CategoryList.Select(x => new SelectListItem() { Text = x.CategoryName.Trim(), Value = x.CategoryID.Trim() }); } <tr> <td> Assigned Category: </td> <td> @Html.DropDownList("CategoryList", CategorySelectList,"Select a Category (Optional)") </td> </tr> |
我将把这当作一个用户模型来处理:
用户服务系统
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Users { [Key] public int UserId { get; set; } [Required] public string UserName { get; set; } public int RoleId { get; set; } [ForeignKey("RoleId")] public virtual DbUserRoles DbUserRoles { get; set; } } |
以及在数据库中用该名称表示表的dbuserroles模型:
德布罗洛斯
1 2 3 4 5 6 7 8 9 | public partial class DbUserRoles { [Key] public int UserRoleId { get; set; } [Required] [StringLength(30)] public string UserRole { get; set; } } |
清理完之后,您应该能够在控制器中创建和填充一组用户角色,如:
1 2 | var userRoleList = GetUserRolesList(); ViewData["userRoles"] = userRolesList; |
并具有以下支持功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | private static SelectListItem[] _UserRolesList; /// <summary> /// Returns a static category list that is cached /// </summary> /// <returns></returns> public SelectListItem[] GetUserRolesList() { if (_UserRolesList == null) { var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem() { Text = a.UserRole, Value = a.UserRoleId.ToString() }).ToList(); userRoles.Insert(0, new SelectListItem() { Value ="0", Text ="-- Please select your user role --" }); _UserRolesList = userRoles.ToArray(); } // Have to create new instances via projection // to avoid ModelBinding updates to affect this // globally return _UserRolesList .Select(d => new SelectListItem() { Value = d.Value, Text = d.Text }) .ToArray(); } |
知识库
我的存储库函数
1 2 3 4 5 6 7 8 9 10 | public class Repository { Model1 db = new Model1(); // Entity Framework context // User Roles public IList<DbUserRoles> GetAllUserRoles() { return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList(); } } |
添加新用户.cshtml
然后在您的视图中执行此操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <table> <tr> <td> @Html.EditorFor(model => model.UserName, htmlAttributes: new { @class ="form-control" } ) </td> <td> @Html.DropDownListFor(model => model.RoleId, new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"],"Value","Text", model.RoleId), htmlAttributes: new { @class ="form-control" } ) </td> </tr> </table> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | @model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel @{ ViewBag.Title ="Detalle"; Layout ="~/Views/Shared/_Layout.cshtml"; } Ingresar Usuario @using (Html.BeginForm()) { @Html.AntiForgeryToken() <hr /> @Html.ValidationSummary(true,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.PersonType, labelText:"Tipo de Persona", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem> { new SelectListItem{ Text="SC", Value ="SC" }, new SelectListItem{ Text="VC", Value ="VC" }, new SelectListItem{ Text="IN", Value ="IN" }, new SelectListItem{ Text="EM", Value ="EM" }, new SelectListItem{ Text="SP", Value ="SP" }, }, htmlAttributes: new { @class ="form-control" }) @Html.ValidationMessageFor(model => model.Employee.PersonType,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.EmployeeGender, labelText:"Genero", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem> { new SelectListItem{ Text="Masculino", Value ="M" }, new SelectListItem{ Text="Femenino", Value ="F" } }, htmlAttributes: new { @class ="form-control" }) @Html.ValidationMessageFor(model => model.Employee.EmployeeGender,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.PersonTitle, labelText:"Titulo", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.PersonTitle, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.PersonTitle,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.PersonFirstName, labelText:"Primer Nombre", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.PersonFirstName, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.PersonFirstName,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.PersonMiddleName, labelText:"Segundo Nombre", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.PersonMiddleName, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.PersonMiddleName,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.PersonLastName, labelText:"Apellido", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.PersonLastName, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.PersonLastName,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.PersonSuffix, labelText:"Sufijo", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.PersonSuffix, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.PersonSuffix,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.DepartmentID, labelText:"Departamento", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment,"DepartmentID","DepartmentName"), htmlAttributes: new { @class ="form-control" }) @Html.ValidationMessageFor(model => model.Employee.DepartmentID,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText:"Estado Civil", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem> { new SelectListItem{ Text="Soltero", Value ="S" }, new SelectListItem{ Text="Casado", Value ="M" } }, htmlAttributes: new { @class ="form-control" }) @Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.ShiftId, labelText:"Turno", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift,"ShiftId","ShiftName"), htmlAttributes: new { @class ="form-control" }) @Html.ValidationMessageFor(model => model.Employee.ShiftId,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.EmployeeLoginId, labelText:"Login", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.EmployeeLoginId, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.EmployeeLoginId,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.EmployeeNationalIDNumber, labelText:"Identificacion Nacional", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.EmployeeNationalIDNumber, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.EmployeeNationalIDNumber,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.EmployeeJobTitle, labelText:"Cargo", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.EmployeeJobTitle, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.EmployeeJobTitle,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.EmployeeBirthDate, labelText:"Fecha Nacimiento", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.EmployeeBirthDate, new { htmlAttributes = new { @class ="form-control datepicker" } }) @Html.ValidationMessageFor(model => model.Employee.EmployeeBirthDate,"", new { @class ="text-danger" }) @Html.LabelFor(model => model.Employee.EmployeeSalariedFlag, labelText:"Asalariado", htmlAttributes: new { @class ="control-label col-md-2" }) @Html.EditorFor(model => model.Employee.EmployeeSalariedFlag, new { htmlAttributes = new { @class ="form-control" } }) @Html.ValidationMessageFor(model => model.Employee.EmployeeSalariedFlag,"", new { @class ="text-danger" }) <input type="submit" value="Guardar" class="btn btn-default" /> @ViewBag.Message @ViewBag.ErrorMessage } |