0

嘗試使用MVC4中的下拉列表創建編輯器模板。我可以得到dropdownlistfor爲這樣的觀點直接工作:將Html.DropDownListFor移動到EditorTemplate中

@Html.DropDownListFor(model => model.Item.OwnerId, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText")) 

但後來爲「泛型化」,並把它變成一個編輯模板,我無法得到它的工作。

以下是我在EditorTemplate部分正在嘗試:

@Html.DropDownListFor(model => model, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText")) 

我收到錯誤:

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'int' does not contain a definition for 'DDLOptions' 

Model.DDLOptions.CustomerOptionsIEnumerable<DDLOptions<int>>類型:

public class DDLOptions<T> 
{ 
    public T Value { get; set; } 
    public string DisplayText { get; set; } 
} 

這是否錯誤與DDLOptions是一個泛型有關嗎?

回答

1

這條線的問題是:

@Html.DropDownListFor(model => model, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText")) 

你的模型只是一個int,基於上面的代碼,但此時你調用部分new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText")也引用Model.DDLOptions,這不存在於模型中的編輯器模板中。你的模型只是一個整數。

有幾種方法可以做到這一點,其中之一是爲您的物品所有者創建自定義模型類並讓其包含ownerID和DDLOptions。另一種方法是將DDLOptions粘貼到ViewBag中,但我通常會遠離那些,因爲我更喜歡使用寫得很好的,特定於視圖的視圖模型。

我希望這會有所幫助。

+1

Thanks M Ob。編輯器模板並不知道全視圖模型,除非您將它傳入,這就是我所做的。下面是你如何將它傳遞給編輯器:@ Html.EditorFor(model => model.Item.Attribute1,new {Options = Model.DDLOptions.ItemAttributeOptions.Attribute1Options})。這裏是我在編輯器中讀取的數據:@ Html.DropDownListFor(model => model,new SelectList((IEnumerable >)ViewData [「Options」],「Value」,「DisplayText」,Model )) –