在controller
中,我正在创建ViewModel
并填充其属性:
[HttpGet]
public ActionResult Index()
{
PermissionViewModel vm = new PermissionViewModel()
{
Users = new List<UserViewModel>()
{
new UserViewModel()
{
Id = 1,
Email = "foo.bar@example.com",
IsSelected = false,
Permissions = new List<SelectListItem>()
{
new SelectListItem() { Value = "1", Text="Admin" },
new SelectListItem() { Value = "2", Text="Customer" },
new SelectListItem() { Value = "3", Text="Employeer" }
},
SelectedPermissionId = 2,
}
},
Pagination = new List<SelectListItem>() {
new SelectListItem() { Value = "10", Text = "10" },
new SelectListItem() { Value = "20", Text = "20"}
},
};
return View(vm);
}
现在,我想显示数据。我遇到Permissions
的问题。我将SelectedPermissionId
设置为2
,所以我希望Customer
将被自动选择。
@foreach (var user in Model.Users)
{
<tr>
<td>@user.Email</td>
<td>
@Html.DropDownListFor(x => user.SelectedPermissionId, user.Permissions)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = user.Id }) | @Html.ActionLink("Delete", "Delete", new { id = user.Id })
</td>
<td>@Html.CheckBoxFor(x => user.IsSelected)</td>
</tr>
}
不幸的是,Admin
被选中。为什么会发生这种情况?
我发现,如果我将Permissions
和SelectedPermissionId
移至PermissionViewModel
,则此操作:
@Html.DropDownListFor(x => x.SelectedPermissionId, Model.Permissions)
正在工作。现在选择了Customer
。但是我必须在UserViewModel
中使用它。.
我找到了解决方案。我必须对此进行更改:
@Html.DropDownListFor(x => user.SelectedPermissionId, user.Permissions)
对此:
@Html.DropDownListFor(x => user.SelectedPermissionId, new SelectList(user.Permissions, "Value", "Text", user.SelectedPermissionId))
有人知道为什么这样做是必要的吗?
答案 0 :(得分:-1)
您的解决方案很好 通常我在下拉列表中使用此代码 我认为这比使用助手
容易<select style="height:auto" class="form-control " id="Permissions" name="Permissions" value="@permission">
<!-- <option value="null"
@if (permission.Text == null) { <text> selected</text> }>
Permissions
</option>
-->
@for (int i = 0; i < ViewBag.Permissions.Count; i++)
{
<option value="@ViewBag.Permissions[i].Text "
@if (permission.Text == ViewBag.Permissions[i].Text ) { <text> selected</text>}>
@ViewBag.Permissions[i].Text
</option>
}
</select>