Adding custom attributes to form elements

Having the ability to quickly generate forms based on the type that the view is tethered to makes creating management screens quick and painless. But what happens when you need to add more information to the forms? Perhaps you need to add a CSS class for formatting or jQuery for selection purposes? This recipe will show you how you can add custom attributes to your form elements.

How to do it...

  1. Jump in from anyone of the last three recipes and navigate to Article.aspx in Views/Home. Let's disable the Title field. We do this by adding a new object to the end of the Html.TextBoxFor() method.
    Views/Home/Article.aspx:
    <div class="editor-label">
    <%: Html.LabelFor(model => model.Title) %>
    </div>
    <div class="editor-field">
    <%: Html.TextBoxFor(model => model.Title, new { disabled = "true" }) %>
    <%: Html.ValidationMessageFor(model => model.Title) %>
    </div>
    
  2. If we wanted to specify more than one attribute for an HTML element, we do that by adding commas to our object. In this case, we will add some alt text to our ID.
    Views/Home/Article.aspx:
    <div class="editor-label">
    <%: Html.LabelFor(model => model.Title) %>
    </div>
    <div class="editor-field">
    <%: Html.TextBoxFor(model => model.Title, new {disabled="true", alt="alt text here"}) %>
    <%: Html.ValidationMessageFor(model => model.Title) %>
    </div>
    

How it works...

A feature I particularly like about ASP.NET MVC is the use of anonymous objects to pass in key/value pairs. One potential gotcha that becomes apparent when applying this technique to HTML attributes, though, is C# reserved words, specifically class. Whenever you need to pass in a reserved word into an anonymous object property, be sure to prepend an @ symbol.

<%: Html.TextBoxFor(model => model.Postcode, new { @class="postcode" }) %>

If you don't like this object syntax (some people don't) then you can also pass in a collection that implements IDictionary instead, but I find it a bit long-winded.

<%: Html.TextBoxFor(model => model.Postcode, new Dictionary<string, object> { { "class", "postcode" } }) %>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset