从列表&LT填充剃刀DropDownList的;对象&gt;在MVC [英] Populating a razor dropdownlist from a List<object> in MVC
问题描述
我有一个模型:
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;
}
}
这是加载视图的控制器:
And here is the Controller that loads the view:
//
// GET: /Admin/AddNewUser
public ActionResult AddNewUser()
{
DbUserRoles Roles = new DbUserRoles();
return View(Roles.GetRoles());
}
我可以在列表中的项目使用 @foreach
循环显示如下:
@foreach (var item in Model)
{
<tr>
<td>
@item.UserRoleId
</td>
<td>
@item.UserRole
</td>
</tr>
}
但我怎么填充,它通过传递模型一个DropDownList,我已经试过
But how do I populate a dropdownlist with the model that is passed through, I have tried
@ Html.DropDownListFor(X =&GT; x.UserRole)
但我有没有运气。
推荐答案
您可以分离出业务逻辑到视图模型,让您的观点有清洁剂的分离。
You can separate out your business logic into a viewmodel, so your view has cleaner separation.
首先创建一个视图模型来存储ID的用户将沿着与将出现在下拉
。
First create a viewmodel to store the Id the user will select along with a list of items that will appear in the DropDown
.
视图模型:
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; }
}
参考文献:
控制器内部创建一个方法让你的的UserRole
列表,并将其转换成将在视图psented $ P $的形式。
Inside the controller create a method to get your UserRole
list and transform it into the form that will be presented in the view.
控制器:
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);
}
参考文献:
现在,该视图模型创建presentation逻辑简化
Now that the viewmodel is created the presentation logic is simplified
查看:
@model UserRoleViewModel
@Html.LabelFor(m => m.SelectedUserRoleId)
@Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)
参考文献:
这将产生:
<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>
这篇关于从列表&LT填充剃刀DropDownList的;对象&gt;在MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!