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.
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>
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>
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" } }) %>