Asp.net mvc 将Html.DropDownListFor移动到EditorTemplate中

Asp.net mvc 将Html.DropDownListFor移动到EditorTemplate中,asp.net-mvc,c#-4.0,asp.net-mvc-4,html.dropdownlistfor,mvc-editor-templates,Asp.net Mvc,C# 4.0,Asp.net Mvc 4,Html.dropdownlistfor,Mvc Editor Templates,正在尝试使用MVC4中的dropdownlist创建编辑器模板。我可以让dropdownlistfor直接在视图中工作,如下所示: @Html.DropDownListFor(model => model.Item.OwnerId, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText")) 但要“泛化”它并将其放入编辑器模板中,我无法让它工作 以下是我在EditorTemplate部分中尝试的内容:

正在尝试使用MVC4中的dropdownlist创建编辑器模板。我可以让dropdownlistfor直接在视图中工作,如下所示:

@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.CustomerOptions
的类型为
IEnumerable

公共类选项
{
公共T值{get;set;}
公共字符串DisplayText{get;set;}
}

此错误是否与DDLPOOTS是通用选项有关?

这一行是问题所在:

@Html.DropDownListFor(model => model, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText"))
根据上面的代码,您的模型只是一个int,但是您也在部分调用
new SelectList(model.DDLOptions.CustomerOptions,“Value”,“DisplayText”)
,引用model.DDLOptions,它在编辑器模板中的模型中不存在。你的模型只是一个整数

有几种方法可以做到这一点,其中之一是为您的项目所有者创建一个自定义模型类,并让它包含ownerID和DDLOptions。另一种方法是将DDL选项粘贴在ViewBag中,但我通常不会这样做,因为我更喜欢使用编写良好、视图特定的视图模型


我希望这能有所帮助。

谢谢我的工作。编辑器模板不知道完整视图模型,除非您传入它,我就是这么做的。以下是将其传递给编辑器的方式:@Html.EditorFor(model=>model.Item.Attribute1,new{Options=model.DDLOptions.ItemAttributeOptions.Attribute1Options})。下面是我在编辑器中读取这些数据的内容:@Html.DropDownListFor(model=>model,newselectlist((IEnumerable)ViewData[“Options”],“Value”,“DisplayText”,model))
@Html.DropDownListFor(model => model, new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText"))