asp.net mvC语言 Move Html.DropDownListFor into EditorTemplate



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

@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<DDLOptions<int>>:

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

这个错误是否与DDLOptions是泛型有关?

这一行就是问题所在:

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

你的模型是一个简单的int,基于上面的代码,但然后你在部分调用new SelectList(Model.DDLOptions.CustomerOptions, "Value", "DisplayText"),引用模型。ddlooptions,它不存在于编辑器模板中的模型中。你的模型只是一个int。

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

最新更新