Question

I want to design my custom editor templates so that they will work even when they are passed a null model. i.e., @Html.EditorForModel() when Model is null.

The problem I have is that when I am in an EditorTemplate, I sometimes need to access one of the properties of the model, and it gets pretty old writing @if(Model != null && Model.[Property] ...)

for example

@model MyObject
@if(Model.BoolProperty) // throws NullReferenceException
{
    <div>...additional stuff here</div>
}

@Html.EditorFor(m => m.OtherProperty)

I considered adding an extension method like the following

public static R GetValue<T, R>(this WebViewPage<T> viewPage, Func<T, R> selector)
{
    if (selector == null) throw new ArgumentNullException("selector");
    if (viewPage == null) throw new ArgumentNullException("viewPage");
    if (viewPage.Model == null) return default(R);
    return selector(viewPage.Model);
}

and using that in the EditorTemplate like this

@model MyObject
@if(this.GetValue(m => m.BoolProperty)) // Safely gets value or false
{
    <div>...additional stuff here</div>
}

@Html.EditorFor(m => m.OtherProperty)

but I want to know if there is a built in or "proper" way to try to access these properties if the model exists, without throwing a NullReferenceException.

Was it helpful?

Solution

Why not checking it once:

@model MyObject
@if (Model == null)
{
    <div>Sorry, nothing to edit here<div>
}
else
{
    ... here you can access the model properties
}

or even outside when calling the template:

@if (Model != null)
{
    @Html.EditorForModel()
}

This way inside the template you no longer need to check if the model is null.

OTHER TIPS

The trick is to make the incoming models in the editor templates the nullable types, int? for integers, DateTime? for dates, bool? for booleans, etc...

So at the top of Integer.cshtml you would have int? instead of int

@model int?
... your code here ...

Say you made a an editor template for money called Currency.cshtml, you would have the following type at the top

@model decimal?
... your code here...

As an FYI, nullable types in .NET have two handy methods: GetValueOrDefault and HasValue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top