我已经完成了这一百次,但不确定这里发生了什么。我有一个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.Pendist
或Model.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'
答案 0 :(得分:3)
您与MVC ModelState发生冲突。创建向下滚动列表时,请确保包含所选值的属性与对象列表的名称不同。另外,不要使用lambda作为默认值,而是直接使用模型项。
@Html.DropDownListFor(model => model.Pendist, (SelectList)ViewBag.PendistList,
Model.Pendist, new { onchange = "ChangeChannel()" })