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