John Edwards
John Edwards

Reputation: 1546

asp.net mvc Modifying CSS of specific items in view model

I have a view model that I am rendering with EditorFor(), and I would like to be able to set the css of specific elements in the model. So for instance:

public class BasicIdentification
{
    //Primitive Types
    [Display(Name = "First Name")]
    public String FName { get; set; }

     [Display(Name = "Last  Name")]
    public String LName { get; set; }

}

If I wanted to set the CSS class for FName and LName, how would I do this? How do I "connect" the css to my model. I want to be able to use EditorFor() an dhave it render the way I want it to.

Upvotes: 0

Views: 887

Answers (3)

Matt Houser
Matt Houser

Reputation: 36053

Create an EditorTemplate for your BasicIdentification class called BasicIdentification.cshtml.

<table>
  <tbody>
    <tr>
      <td>
        @Html.DisplayFor(model => model.FName)
        @Html.EditorFor(model => model.FName)
      </td>
      <td>
        @Html.DisplayFor(model => model.LName)
        @Html.EditorFor(model => model.LName)
      </td>
    </tr>
  </tbody>
<table>

Then whenever you do @Html.EditorForModel() and your model is your BasicIdentification class, then the above HTML will be generated.

Edit: Additional information about Editor Templates: http://dineshkumara.blogspot.ca/2011/06/mvc-3-razor-editor-template.html

Upvotes: 0

Nick Larsen
Nick Larsen

Reputation: 18877

You don't want to "set the CSS" per say, but I don't see a problem with including the state of in your view model which can then be translated into an HTML class which you can use to style it appropriately in your view.

Upvotes: 0

Sam North
Sam North

Reputation: 61

In the View you would see something like this by default

<div class="display-label">
    @Html.DisplayNameFor(model => model.LName)
</div>
<div class="display-field">
    @Html.TextBoxFor(model => model.LName)
</div>

To add a CSS class or something you simply do this.

@Html.TextBoxFor(model => model.LName, new { @class="classname" })

class itself is a reserved word for .NET so the @class just means to use the HTML class attribute.

Upvotes: 6

Related Questions