Ciel
Ciel

Reputation: 17752

EditorFor is not getting the right Editor in ASP.NET MVC 3.0

I have 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

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?

Upvotes: 1

Views: 1197

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 4

Jay
Jay

Reputation: 6294

This is because your model is AspectViewModel, but your view name is Aspect. They must match exactly.

Upvotes: 0

Related Questions