adding a class to EditorFor - razor c#

asp.net-mvc, c#, editorfor, razor

Solution

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")

Problem

(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 :(

Original source