ASP.NET Razor 2.0 view engine tip: checked or not checked?

Posted: (EET/GMT+2)

 

The Razor view engine, especially nice in ASP.NET MVC applications, contains many tricks that let you code faster and cleaner. One of my favorite tricks in Razor 2.0 (as in ASP.NET MVC 4) is the ability to conditionally set HTML attribute values, or omit the attribute altogether, automatically.

Let's take an example of HTML input controls, like a check box or a radio button. With these controls, you often need a way to programmatically control the checked state of these controls, especially in "Edit" views.

As you are aware, to make a box/button checked, you add the "checked" attribute to it, and if you don't want to see the box/button unchecked, you simply omit this attribute altogether. Traditionally, this logic requires an if statement, which doesn't look very clean. Razor to the rescue: it lets you write HTML like this:

<input id="CheckboxOption1" type="checkbox" checked="@ViewBag.Option1" />

Notice how the "checked" attribute has been specified and the value for it is retrieved using the ViewBag property. Now, let's look at the results for the three different states of the ViewBag.Option1 member as specified in the C# controller action method: true, false and not set (null):

  • ViewBag.Option1 = true. This renders the input tag’s element like this: checked="checked".
  • ViewBag.Option1 = false. This does not render the checked attribute (nor its value) at all.
  • ViewBag.Option1 is not set. Works the same as setting the value to false: the checked attribute is not rendered to the resulting HTML code at all. No exceptions are raised.

Neat, isn't it? Enjoy Razor!