Asp.net-Mvc

無法讓 DropDownListFor 在 MVC3 中的 EditorFor 上工作

  • June 12, 2011

我有一個非常簡單的問題,有一個我找不到的解決方案。

給定以下模型:

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

我很難理解這兩者之間的區別。我嘗試了各種解決方法來進行故障排除,要麼得到相同的錯誤,要麼出現其他錯誤。

提前致謝。

沒有這樣的重載:

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

助手的第二個參數DropDownListFormusty 是 a SelectList。所以:

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

引用自:https://stackoverflow.com/questions/6319635