adding a class to EditorFor - razor c#

6.5k views Asked by At

(The editor is for a DateTime property called "ADate"

I am trying this but it does not work.

@Html.EditorFor(model => model.ADate, new { cssClass = "date" } )

So I tried this:

@Html.TextBoxFor(model => model.ADate, new { @class = "date" })

but it outputs type = text.. ofcourse it does.

So I tried a template... I added a folder in shared:

Shared/EditorTemplates

and then I created a .cshtml partial view called Date.cshtml

Now what on earth do I put inside it :O...

I have tried to understand lots of posts and stack overflow entries but it's not sinking in.

The goal is to attach a datepicker to the class ".date" across the entire app where ".date" class is used... The TextBoxFor works with my adding class part... but as I said, the type changes from date to text :(

3

There are 3 answers

2
Dimitar Dimitrov On BEST ANSWER

Ok so this is what you can do:

In your EditorTemplates folder create a template called DateTime.cshml (the name will resolve automatically if you use it for dates, otherwise you have to specify it when using it). Then in it:

@model System.DateTime

@Html.TextBox(
   string.Empty, 
   Model.ToString("yyyy-MM-dd"),
   new { @class="datepicker", @type = "date"})

Using the last parameter you can specify any html attribute (class, data, type etc.).

Then you use it like this:

@Html.EditorFor(x => x.ADate)

In case you chose to name your template with a different name you can specify it by invoking another overload:

@Html.EditorFor(x => x.ADate, "MyOtherAwesomeTemplate")
0
ataravati On

The EditorFor html helper does not render a date picker for your DateTime attributes (if that's what you want to do). The default EditorFor for DateTime is a text input. If you want to use a date picker, you'll have to use jQuery DatePicker (or any other third party date picker).

Also, the EditorFor helper does not have a parameter for html attributes. If you want to assign a class, you'll have to use TextBoxFor.

In your main View, use the EditorFor like this:

@Html.EditorFor(model => model.ADate)

Then, in your Editor Template (Date.cshtml), you'll have:

@model System.DateTime

<script type="text/javascript">
    $(function () {
        $(".date").datepicker();
    });
</script>

@Html.TextBox("", Model.ToString("d"), new { @class = "date" })

You can download the jQuery UI from here: Download jQuery UI

And, you can learn more about the jQuery DatePicker here: jQuery DatePicker

0
Bilal On

You can do this

@Html.EditorFor(model => model.ADate)

<style type="text/css">

#ADate
{
 @* your css properties goes here *@
}
</style>

this works fine for MVC3 Razor