1

How can I add html attributes such as maxlength, style, css and ... to Html.EditorFor()?

Ghooti Farangi
  • 19,926
  • 15
  • 46
  • 61
  • possible duplicate of [Html attributes for EditorFor() in ASP.NET MVC](http://stackoverflow.com/questions/3735400/html-attributes-for-editorfor-in-asp-net-mvc) – Bertrand Marron Mar 10 '11 at 11:31

2 Answers2

4

This is way late but maybe someone else will find this helpful.

Why walk the long way? I suppose we are dealing with a string since you want to add a maxlength attribute. Then you can just use Html.TextBoxFor instead of Html.Editorfor.

TextBoxFor accepts html attributes.

@Html.TextBoxFor(model => model.Name, new{ maxlength = 50 })
Rafay
  • 30,950
  • 5
  • 68
  • 101
user885472
  • 41
  • 2
  • this doesn't help though when you specifically have to deal with Editor templates. For example if you have a template for Decimals where the format has to be dealt with specifically and a standard TextBoxFor won't do the trick. – Jacques Aug 25 '14 at 06:45
0

I've been wrestling with the same issue today, and since I can't change my model (not my code) I had to come up with a better way of handling this. It's a bit brute force, but it should work for 99% of cases I might encounter.

In my Boolean.cshtml editor template:

@model bool?

@{
    var attribs = new Dictionary<string, object>();
    var validAttribs = new string[] {"style", "class", "checked", "@class",
        "classname","id", "required", "value", "disabled", "readonly", 
        "accesskey", "lang", "tabindex", "title", "onblur", "onfocus", 
        "onclick", "onchange", "ondblclick", "onmousedown", "onmousemove", 
        "onmouseout", "onmouseover", "onmouseup", "onselect"};

    foreach (var item in ViewData) 
    {
        if (item.Key.ToLower().IndexOf("data_") == 0) 
        {
            attribs.Add(item.Key.Replace('_', '-'), item.Value);
        } 
        else 
        {
            if (validAttribs.Contains(item.Key.ToLower()))
            {
                attribs.Add(item.Key, item.Value);
            }
        }
    }
}

@Html.CheckBox("", Model.GetValueOrDefault(), attribs)
Isochronous
  • 1,076
  • 10
  • 25