9

我有一個非常簡單的問題,它有一個我找不到的解決方案。無法讓DropDownListFor在MVC3的EditorFor上工作

考慮以下模型:

public class InfoViewModel 
{ 
    public SelectList States { get; set; } 

    [DisplayName("State")] 
    public string State { get; set; } 
} 

以下工作在我看來罰款:

@Html.DropDownListFor(m => m.State, Model.States) 

但是,如果我試圖拉進編輯模板,這個(命名爲 「的SelectList」),如:

@model System.String 
@Html.DropDownListFor(m => m, ViewData["selectList"]) 

然後用EditorFor打造的下拉列表:

@Html.EditorFor(m => m.State, "SelectList", new { selectList = Model.States }) 

它失敗,出現以下錯誤:

'System.Web.Mvc.HtmlHelper<string>' does not contain a definition for 
'DropDownListFor' and the best extension method overload 
'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty> 
(System.Web.Mvc.HtmlHelper<TModel>, 
System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, 
System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' 
has some invalid arguments 

我有一個很難理解這兩者之間的區別。我嘗試了各種解決方法來解決問題,並且得到相同的錯誤或其他內容。

在此先感謝。

+0

謝謝...,你的囚犯是有用的作爲我的答案/// – 2015-05-28 06:11:13

回答

10

有沒有這樣的過載:

@Html.DropDownListFor(m => m, ViewData["selectList"]) 

DropDownListFor輔助黴味的第二個參數是SelectList。所以:

@Html.DropDownListFor(m => m, (SelectList)ViewData["selectList"]) 
+0

謝謝,達林,這就是它。我應該意識到這一點。 – 2011-06-13 03:23:33