Sunday 7 April 2013

Applying CSS classes in ASP.NET MVC fields

I'm a total newbie when it comes to ASP.NET MVC and a few days back I was looking at issue where the font size was different on two text controls on the same form. One of the controls was a single line text box, while the other was

This is the original code, which I thought would apply the fields class to the controls:

<fieldset>              
   <div class="label">              
     @Html.LabelFor(model => model.Title)              
   </div>              
   <div class="field">              
     @Html.EditorFor(model => model.Title, new { autocomplete = "off" })          
     @Html.ValidationMessageFor(model => model.Title)              
   </div>              
   <div class="label">              
     @Html.LabelFor(model => model.Details)              
   </div>              
   <div class="field">              
     @Html.TextAreaFor(model => model, new { rows=10, cols=50 })            
     @Html.ValidationMessageFor(model => model.Details)              
   </div>              
</fieldset>              

The problem was that this wasn't working and I couldn't work out why. After looking at the styles one too many times, hangs head in shame, I realized that it was picking up the styles from the user agent rather than the css file.

A bit of searching revealing that this is what I should have done instead:

<fieldset>              
   <div class="label">              
     @Html.LabelFor(model => model.Title)              
   </div>              
   <div class="field">              
     @Html.EditorFor(model => model.Title, new { autocomplete = "off", @class=editor })              
     @Html.ValidationMessageFor(model => model.Title)              
   </div>              
   <div class="label">              
     @Html.LabelFor(model => model.Details)              
   </div>              
   <div class="field">              
     @Html.TextAreaFor(model => model,10,50, new {@class=editor })            
     @Html.ValidationMessageFor(model => model.Details)              
   </div>              
</fieldset>              

No comments:

Post a Comment