3

Is there any better way to code razor cshtml that checks for null for nested object so it wont throw null exception error on the container object if the container is null. For example :

page.cshtml

Hello @obj1.obj2.prop3

will throw error if obj1 is null or obj1.prop3is null, but

Hello @Html.DisplayFor(m => obj1.obj2.prop3)

can check for null on obj1 or obj1.obj2 so it won't throw error

Hello @(obj1 == null? "" : (obj1.obj2 == null? "" : obj1.obj2.prop3))

is just too lengthy

4

1 回答 1

1

You can try creating your own html helper:

static class MyOwnHtmlHelpers
{
    public static string EmptyIfNull<TModel>(this HtmlHelper<TModel> helper, Func<TModel, string> accessor)
    {
        try
        {
            var result = accessor.Invoke(helper.ViewData.Model);
            return result;
        }
        catch(NullReferenceException)
        {
            return string.Empty;
        }
    }
}

And then use it like this:

@Html.EmptyIfNull(m => obj1.obj2.prop3)
于 2013-02-20T09:04:46.700 回答