Scott Smith

Blog Tutorials Projects Speaking RSS

Using @ and _ With HTML Helpers in Razor Views

Here is a tip for you .NET developers.

When you are using HTML helpers there are times when you need to add extra attributes to the HTML element being produced by the helper. Two attributes that are commonly added are the class and data- attribute. HTML helpers support the ability to pass in an anonymous object for setting these attributes. The helper will take each item out of the anonymous object and add them to the html element as attributes.

Here is simple example that sets the id of the checkbox element:

1
@Html.CheckBox("ignore", new { id = "1" })

This works just fine when things are simple, but what if you want to set the class attribute? If you were to try the following, it would fail:

1
@@Html.CheckBox("ignore", new { class = "bananas" })

The reason this fails is because class is a reserved keyword in C#. The way to get around this to preface the keyword with @ which tells the C# compiler to treat the word as a symbol.

1
@@Html.CheckBox("ignore", new { @class = "bananas" })

Now, say you want to add a data-name attribute to the element. If you were to create like the following, it would fail:

1
@@Html.CheckBox("ignore", new { @class = "bananas", data-name = "bit" })

The reason this fails is because the C# compiler does not allow dashes (-) in variable names. Not to worry though, this is easily handled by using the underscore (_) character in place of the dash. The underscore will be automatically replaced with a dash at run time.

1
@@Html.CheckBox("ignore", new { @class = "bananas", data_name = "bit" })

So the final output would look like this:

1
<input class="bananas" data-name="bit" id="ignore" name="ignore" type="checkbox" value="true">