EditorFor没有在ASP.NET MVC 3.0中获得正确的编辑器

时间:2011-05-25 21:16:30

标签: asp.net-mvc-3 mvc-editor-templates

我有一种情况,我希望将自定义EditorTemplate与ViewModel一起使用。所以我有我的ViewModel ......

class Aspect {
}
class AspectViewModel {
}

然后我的EditorTemplate

    • 共享
      • EditorTemplates
        • Aspect.cshtml

Aspect.cshtml

@model AspectViewModel

//其他html

然后在另一个AspectViewModel视图中,我调用@Html.EditorFor(model => model),但它不起作用。它仅在我使用硬编码字符串@Html.EditorForModel("Aspect")时才有效。

知道为什么没有被召唤?

2 个答案:

答案 0 :(得分:3)

如果编辑模板强烈输入AspectViewModel.cshtml,则应将其命名为AspectViewModel。然后你所要做的就是:

@model AspectViewModel
@Html.EditorForModel()

@model SomeViewModel
@Html.EditorFor(x => x.Aspect)

Aspect的{​​{1}}属性属于SomeViewModel类型。

约定是编辑器/显示应该被命名为您调用它的属性的类型而不是该属性的名称。

他们也非常适合收藏。例如,如果您具有以下属性:

AspectViewModel

你使用:

public class SomeViewModel
{
    public IEnumerable<AspectViewModel> Aspects { get; set; }
}

然后将为此集合的每个元素呈现@model SomeViewModel @Html.EditorFor(x => x.Aspects) 编辑器模板。多亏了这一点,你真的不再需要在你的视图中写下~/Views/Shared/EditorTemplates/AspectViewModel.cshtml / for个循环。

答案 1 :(得分:0)

这是因为您的模型为AspectViewModel,但您的视图名称为Aspect。他们必须完全匹配。