I’ve got a model like this:
public class ParentViewModel
{
public class ChildViewModel { get; set; }
// other properties
}
Then in the view for ParentViewModel, i do this:
@Html.EditorFor(model => model.ChildViewModel)
And it executes my custom editor template, even when Model.ChildViewModel is null. Why? I thought MVC was smart enough to only render the view/template when it has a value. (e.g the default template for null is to not render anything).
Because at the moment, i would have to wrap the HTML in my custom editor template with:
@if (Model != null)
Which seems very silly.
Is this a known problem?
I’m on ASP.NET MVC 3, Razor.
Rather than testing for null before your partial or inside it you can use a new extension method. This also gives you more options for how to deal with a null model. Here’s the extensions I use, it will test for null and either return an empty string or a different partial on a null result. This can be particularly helpful on things like pagers where the page is out of range as you can have a separate partial with your “no results” information.
Edit
Sorry I misready the question being about EditorTemplates. However I see no reason that the same approach can’t work for EditorFor, you just have a few more method signatures to replicate.