EditorFor is not getting the right Editor in ASP.NET MVC 3.0
I hav开发者_运维问答e a situation where I want to use a custom EditorTemplate
with a ViewModel. So I have my ViewModel...
class Aspect {
}
class AspectViewModel {
}
then my EditorTemplate
- Views
- Shared
- EditorTemplates
- Aspect.cshtml
- EditorTemplates
- Shared
Aspect.cshtml
@model AspectViewModel
// other html
Then in another view that takes AspectViewModel
, I call @Html.EditorFor(model => model)
, but it does not work. It only works if I use a hard-coded string @Html.EditorForModel("Aspect")
.
Any idea why it isn't being called?
You should name the editor template AspectViewModel.cshtml
if it is strongly typed to AspectViewModel
. Then all you have to do is:
@model AspectViewModel
@Html.EditorForModel()
or
@model SomeViewModel
@Html.EditorFor(x => x.Aspect)
where the Aspect
property of SomeViewModel
is of type AspectViewModel
.
The convention is that the editor/display should be named as the type of the property you are calling it on and not the name of this property.
They also work greatly with collections. For example if you have the following property:
public class SomeViewModel
{
public IEnumerable<AspectViewModel> Aspects { get; set; }
}
and you use:
@model SomeViewModel
@Html.EditorFor(x => x.Aspects)
then the ~/Views/Shared/EditorTemplates/AspectViewModel.cshtml
editor template wil be rendered for each element of this collection. Thanks to this you really no longer need to ever write for
/foreach
loops in your views.
This is because your model is AspectViewModel
, but your view name is Aspect
. They must match exactly.
精彩评论