OdeToCode IC Logo

A Better Razor IsNullOrEmpty Statement

Tuesday, June 28, 2011

This post is a play on Phil's "A Better Razor Foreach Loop".  If you aren't familiar with templated delegates in Razor, you can follow the links in Phil's post.

Something I don't like to see in a view is the if null or empty check.

@if (!String.IsNullOrEmpty(User.Identity.Name)) { 
    <span>Logged in as: @User.Identity.Name</span>
}

There are a number of ways to remove the check, but the knowledge in Phil's post give you one more option -  the HTML helper option.

public static class RazorExtensions
{    
    public static HelperResult Maybe(this string @string,
                                     Func<object, HelperResult> template)
    {
        return new HelperResult(writer =>
        {
            if (!String.IsNullOrEmpty(@string))
            {
                template(@string).WriteTo(writer);
            }
        });
    }
}

Now the view code can look like this:

@User.Identity.Name.Maybe(@<span>Logged in as: @item</span>)

Better? Or Worse?