DropDownListFor没有自动选择属性

时间:2018-06-26 09:29:37

标签: c# asp.net asp.net-mvc

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被选中。为什么会发生这种情况?

编辑

我发现,如果我将PermissionsSelectedPermissionId移至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))

有人知道为什么这样做是必要的吗?

1 个答案:

答案 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>