39

I'm trying to add a css class to a textbox. This is what I have in my view:

<%: Html.EditorFor(m => m.StartDate) %>

I tried following the instructions at this link by making my code:

<%: Html.EditorFor(m => m.StartDate, new { @class: "datepicker" }) %>

But I get a compiler error saying:

Syntax error, ',' expected

What am I doing wrong here?

Community
  • 1
  • 1
Steven
  • 18,761
  • 70
  • 194
  • 296

8 Answers8

78

With MVC3, I kept banging my head because I couldn't get this to work. I didn't want to create a whole EditorTemplate for just adding one class.

Well, instead of using EditorFor, use TextBoxFor, with of course the equals sign like so:

@Html.TextBoxFor(m=> m.ZipCode, new { @class = "zip" })
Aaron Daniels
  • 9,563
  • 6
  • 45
  • 58
  • 28
    This doesn't work when you need to have your data in editmode. I.e., otherwise decorating your model with something like `[DisplayFormat(DataFormatString = "{0:dd-MMMM-yyyy}", ApplyFormatInEditMode = true)]` won't work. – Abel Apr 16 '12 at 13:27
  • Any solution to this issue yet? – akd Jun 24 '14 at 11:12
24

I would HIGHLY suggest using Editor Templates. It's definitely the "right" way to style your EditorFor.

You can tell a model property to use an Editor Template in two different ways.

The first (the simplest) is to create an editor template for a certain data type - DateTime for example.
The second way to do it is to set it declaratively in your DataAnnotations by using a UIHint.

Edit
I'd also like to add that you should use the "date" type in your input field so that even when JavaScript is disabled, your user can stills see a native datepicker (only valid on modern HTML5 browsers)
<input id="meeting" type="date" value="2011-01-13"/>

Chase Florell
  • 46,378
  • 57
  • 186
  • 376
5

I guess a quick and dirty way to do this would be in jQuery, yes?

$(document).ready(function () {
    $('#StartDate').addClass('datepicker');
});
egbrad
  • 2,387
  • 2
  • 23
  • 27
  • and when javascript is turned off? – Chase Florell Oct 11 '11 at 15:13
  • 23
    Then your datepicker probably won't work anyway. Are people really programming web applications with the expectation that they will work with javascript disabled? – egbrad Oct 19 '11 at 15:00
  • yes, they absolutely are. And for the record, modern browsers can have javascript disabled, and still show a datepicker if you use the HTML5 `` – Chase Florell Oct 19 '11 at 15:36
  • 3
    Then what do you do if the user doesn't have a modern browser? – egbrad Oct 19 '11 at 19:08
  • 2
    Seriously dude? Read up on [Progressive Enhancement](http://en.wikipedia.org/wiki/Progressive_enhancement). You build your website so that it works for EVERYONE, then progressively enhance it for people who have the better/newer browsers. – Chase Florell Oct 19 '11 at 21:21
  • 32
    Go ahead and disable javascript, refresh this page, and try to enter a reply. You can't. It is reasonable to expect your users to have javascript enabled, or certain things like a datepicker will not work. They could still type the date in in that scenario. – egbrad Oct 24 '11 at 21:23
4

Ideally, you should use the Editor Templates. I got around this issue by using the Editor Template inside the MvcHtmlString.Create() which will let you rebuild the actual HTML code. Of course, you'll want to copy everything in the "class" section to keep the Editor Template as useful as possible.

I tried many of the suggestions above, but eventually, I settled on this, because I think it's less complicated and it lets me continue using Editor Templates:

@MvcHtmlString.Create(Html.EditorFor(m => m.StartDate).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line datepicker\""))
CIA
  • 302
  • 1
  • 5
  • 16
  • 2
    and then one of this days there's an update to the `text-box single-line` and all goes to stop..., sorry, not the best idea to rely on `Replace()` – balexandre Feb 22 '13 at 00:52
  • It's relatively simple to resolve the problem if `text-box single-line` is updated in the future. I'll just update the code accordingly. Until there's an option to use the Editor Templates and allow me to easily/simply add/replace classes, I'm OK with this. – CIA Feb 23 '13 at 00:31
  • I would love to! That's why I'm here. It's great to see all these people who have given great suggestions to solving a problem. Hey, I have an idea! You can help me by giving me amazing suggestions/alternatives, too! Unless you prefer bashing people. 'cause that would only be adding to the bad stereotype that programmers are cynical and anti-social people who think themselves better than everyone else while snickering at inside jokes you whisper to yourself when no one is listening. I mean, who does that right? It's not like you only commented, because you wanted attention. Right? – CIA Feb 23 '13 at 01:36
  • 2
    How about @MvcHtmlString.Create(Html.EditorFor(m => m.StartDate).ToString().Replace("class=\"", "class=\"datepicker ")). This way we may not worry about further update to class attribute. – longbkit Apr 10 '13 at 14:16
4

I know this is an old question but thought I could contribute so here goes. I had the same problem and wanted to avoid making Editor Templates. I just wanted a generic handle everything solution that would allow me to specify html attributes when using Html.EditorFor in a view.

I really liked CIAs answer, but I expanded on it a bit so that you can pass in any attributes you need. I created an extra Html.EditorFor method that accepts html attributes:-

public static class EditorForExtentions
{
    public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Object htmlAttributes, bool extendAttributes)
    {
        string value = html.EditorFor(expression).ToString();

        PropertyInfo[] properties = htmlAttributes.GetType().GetProperties();
        foreach (PropertyInfo info in properties)
        {
            int index = value.ToLower().IndexOf(info.Name.ToLower() + "=");
            if (index < 0)
                value = value.Insert(value.Length - (value.EndsWith("/>") ? 2 : 1), info.Name.ToLower() + "=\"" + info.GetValue(htmlAttributes, null) + "\"");
            else if (extendAttributes)
                value = value.Insert(index + info.Name.Length + 2, info.GetValue(htmlAttributes, null) + " ");            
        }

        return MvcHtmlString.Create(value);
    }
}

You can call it in a view like this

<%=Html.EditorFor(m => m.StartDate, new { @class = "datepicker" }, true)%>

It uses the normal Html.EditorFor method to get the html string, then injects the html attributes needed.

user1573618
  • 1,696
  • 2
  • 20
  • 38
3

There is no overload for EditorFor that allows you to set HtmlProperties. (IDictionary htmlAttributes)

This link explains how to do it:

http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-2D00-ASP.Net-MVC-2.0-Beta_2D00_1.aspx

Adam Maras
  • 26,269
  • 6
  • 65
  • 91
santiagoIT
  • 9,411
  • 6
  • 46
  • 57
1

I was looking for a solution to apply a style to a specific box generated by the @HTML.EditorFor helper method.

The question was regarding setting a CSS class for @HTML.EditorFor but for anyone who wants to edit the style for a single element.. you can, for example, try this:

In my block, I added a style based on the ID generated by the helper: ..

<style> 
    #EnrollmentInfo_Format
    {
        width:50px;
        font: normal 100% 'Lucida Grande',Tahoma,sans-serif;
        font-size: 11px;
        color: #2e6e9e;
    }
</style>

and then in my page (i'm doing this in a partial view):

@Html.EditorFor(e => e.EnrollmentInfo.Format)
c121hains
  • 95
  • 1
  • 6
  • I've been trying, unsuccessfully, for months to find a solution for styling these dang Helper tags, and your solution was exactly what I needed! Thank you! – PKD Feb 06 '15 at 19:03
-3

Here's a very simple solution: Remove the double quotes from "datepicker" and retype them back into Visual Studio and it should work.

I had the same problem. I copied/pasted sample code from the web and the code had a special type of quote which caused the "," syntax problem. I know it's really not obvious.

Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
jade01
  • 1