Ghooti Farangi
Ghooti Farangi

Reputation: 20156

html attributes for editorfor

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

Upvotes: 1

Views: 7616

Answers (2)

Isochronous
Isochronous

Reputation: 1090

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)

Upvotes: 0

user885472
user885472

Reputation: 41

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

Upvotes: 4

Related Questions