指定ASP MVC 3 DropDownListFor的默认值

时间:2013-05-01 17:40:37

标签: asp.net-mvc asp.net-mvc-3 html.dropdownlistfor dropdownlistfor

我已经完成了这一百次,但不确定这里发生了什么。我有一个DropDownListFor我在控制器中填充,如此

        var mktsegments = from p in db.ChannelMarketSegment
                          where (p.ChannelCode != "0")
                          select p;
        ViewBag.Pendist = new SelectList(mktsegments, "Pendist", "Pendist");

在视图中,我尝试使用Pendist值设置此下拉列表的默认值。

编辑:Pendist是通过mktsegments查询提取到Linq的每个项目中的字段。

    <div class="M-editor-label">
        @Html.LabelFor(model => model.Pendist)<span class="req">*</span>
    </div>
    <div class="M-editor-field">
        @Html.DropDownListFor(model => model.Pendist,
         (SelectList)ViewBag.Pendist, new { onchange = "ChangeChannel()" }) 
    </div>

但是,所有这一切都将列表中的第一个值设置为默认值。如果我尝试将model => model.PendistModel.Pendist添加为DropDownListFor中的第三个参数

        @Html.DropDownListFor(model => model.Pendist,
      (SelectList)ViewBag.Pendist, model => model.Pendist, new { onchange = "ChangeChannel()" })

我得到以下错误

(适用于model => model.Pendist

Cannot convert lambda expression to type 'string' because it is not a delegate type

(适用于Model.Pendist

'Model' confilcts with the declaration 'System.Web.Mcv.WebViewPage<TModel>.Model'

1 个答案:

答案 0 :(得分:3)

您与MVC ModelState发生冲突。创建向下滚动列表时,请确保包含所选值的属性与对象列表的名称不同。另外,不要使用lambda作为默认值,而是直接使用模型项。

@Html.DropDownListFor(model => model.Pendist, (SelectList)ViewBag.PendistList, 
    Model.Pendist, new { onchange = "ChangeChannel()" })