ASP.NET MVC Conditional Render Helper

1 minute read

Many of us have probably encountered the need for this on various projects. The scenario is simple, we have optional fields that a user may or may not enter values for, and we would like to hide them from display if they were not filled in.

The above screenshot could use some cleaning up. Ideally those fields that contain no data should be hidden from the rendered HTML. Our first attempt might look something like below, but hopefully, after 1 or 2 copy pastes any developer will realize this should be handled differently. Who among us has run into maintaining code looking like this?

Ok let’s go back to the drawing board. The MVCToolkit comes with many extension methods for the HtmlHelper class that ships with the ASP.NET MVC framework. The Html object is accessible to every MVC Page, and will prove invaluable for generating inputs like  RadioButtonLists, DropDownLists, Submit buttons, etc. Let’s see how it will look if we add a ConditionalRender extension to the HtmlHelper class. Our ideal code will look something like this:

That looks pretty good, but we need a mechanism to tell the ConditionalRender helper how to format the returned HTML. To do this, we can add a string variable to define the format we want returned and pass it to the helper, as shown below:

Excellent, as we can see below, the fields the user entered are displayed nicely for us, while the fields that were left empty are not rendered to our output HTML at all.

Here is the code the extension method. Just be sure to <add namespace=”MattHidinger.Extensions”> to your web.config, so that the extension method will be imported to all of your Pages.

namespace MattHidinger.Extensions
{
    public static class HtmlExtensions
    {
        public static string ConditionalRender(this HtmlHelper helper, object input, string label, string format)
        {
            if (input == null)
                return string.Empty;
 
            return string.Format(format, label, input.ToString());
        }
    }
}

Leave a Comment