DropDownListFor()没有填充ViewModel中预先选择的项目?

时间:2011-11-24 13:36:13

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

在我的项目中,DropDownListFor(x => x代码位于EditorTemplate中。它用于填充数据表,其中一个字段是下拉列表。虽然所有内容都呈现没有问题,下拉列表不会默认为我在ViewModel中设置的预选项目。我没看到什么?

代码如下:

视图模型:

public class FooDetailViewModel : ViewModelBase
{
    public List<FooPermissionObject> FooPermissions { get; set; }
}

强类型模型对象:

public class FooPermissionObject
{
    public string Name { get; set; }
    public int Reason { get; set; }
    public IEnumerable<SelectListItem> Reasons { get; set; }
    public bool Selected { get; set; }
}

控制器:

var viewModel = new StockLineManagementDetailViewModel();

using (_model)
{
    foreach (var company in _model.GetAllRecords<Company>())
    {
        var permissionModel = new FooPermissionObject
        {
            Name = company.Name,
            Selected = true,
            Reasons = _model.GetAllRecords<FooPermissionReason>()
                    .ToList()
                    .Select(x => new SelectListItem
                    {
                        Value = x.FooPermissionReasonId.ToString(),
                        Text = x.FooPermissionReasonDesc
                    }),
            Reason = record.FooPermissionReasonId
        };

        viewModel.FooPermissions.Add(permissionModel);
   }
}

观点:

<table id="myTable" class="tablesorter" style="width:98%">
    <thead>
         <tr>
        <th>
            Name
        </th>
        <th>
            Excluded
        </th>
        <th>
            Reason for Exclusion
        </th>
       </tr>
    </thead>
    <tbody>
        @Html.EditorFor(x => x.FooPermissions)
    </tbody>
</table>

EditorTemplate:

@model FooPermissionObject
<tr>
    <td>
        @Html.DisplayFor(x => x.Name, new { @readonly = "readonly"})
        @Html.HiddenFor(x => x.Name)
    </td>
    <td>
        @Html.CheckBoxFor(x => x.Selected)
    </td>
    <td>
        @Html.DropDownListFor(x => x.Reason, Model.Reasons)
    </td>
</tr>

任何人都有任何想法,为什么这不会填充DropDownListFor与由Reasons集合中的Reason值表示的Object?

2 个答案:

答案 0 :(得分:1)

我看不到您在选择列表中设置selected = true的任何代码。您正在设置FooPermissionObject的Selected属性,但这与您的下拉列表绑定到reason集合无关。你想要这样的东西:

.Select(x => new SelectListItem
{
    Value = x.FooPermissionReasonId.ToString(),
    Text = x.FooPermissionReasonDesc,
    Selected = (Some codition or other)
})

根据您的标准更换某些条件或其他条件,以说明应选择哪个项目。

编辑:

更好的方法可能如下:

Reasons = new SelectList(_model.GetAllRecords<FooPermissionReason>(),
                         "FooPermissionReasonId",
                         "FooPermissionReasonDesc",
                         record.FooPermissionReasonId)

SelectList构造函数的参数是:绑定集合,值字段,文本字段,选定值。

答案 1 :(得分:0)

编辑 另一种方式(现在是单向)可以设置Selected属性,同时投影到SelectListItem - 列表(如果需要)。

关于这个主题的好文章可以在那里找到:http://codeclimber.net.nz/archive/2009/08/10/how-to-create-a-dropdownlist-with-asp.net-mvc.aspx