1

我已经这样做了一百次,但不确定这里发生了什么。我有一个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.PendistorModel.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'

4

1 回答 1

3

您与 MVC ModelState 冲突。创建 Drow Down 列表时,请确保保存所选值的属性与对象列表的名称不同。另外,不要使用 lambda 作为默认值,而直接使用模型项。

@Html.DropDownListFor(model => model.Pendist, (SelectList)ViewBag.PendistList, 
    Model.Pendist, new { onchange = "ChangeChannel()" })
于 2013-05-01T17:55:53.230 回答