1

我已经完成了这一百次,但不知道这里发生了什么。我有一个DropDownListFor,我在控制器中填充像这样为ASP MVC指定默认值3 DropDownListFor

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

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

编辑: Pendist是存在于每个项目通过Linq查询被拉入mktsegments的字段。

<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'

+0

是'Pendist'对象列表还是需要选择的值? – Jared 2013-05-01 17:46:04

+0

'Pendist'是'mktsegments'中每个项目中包含的一个字段,我会将该信息添加到该帖子中。 Thx – NealR 2013-05-01 17:48:12

回答

3

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

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

我总是忘记这个......谢谢! – NealR 2013-05-01 17:56:59