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