ASP.NET MVC Razor. How to do not replace non us characters on fields IDs?

If my POCO class does have an attribute like this:

public int Número {get; set;}

and them write it on my view:

@Html.EditorFor(model => model.Número)

it renders a input with underscores replacing the non standard us characters, like this:

<input name="Número" id="N_mero" type="text" />

Is possible to avoid it somehow? I would like to preserve the non standard characters on input ids in order to easily query with Javascript.

Answers:

Answer

You can use the EditorFor overload that accepts a view data object to override the value used for the id attribute:

@Html.EditorFor(model => model.Número, new { htmlAttributes = new { id = nameof(Model.Número) } })

EDIT: It's not quite a global configuration solution where you can just flip a switch and have all your existing code work, but with an extension method it'll be easier going forward:

public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, bool overrideId = false)
{
    if (overrideId)
    {
        var propertyExpression = expression.Body as MemberExpression;
        if (propertyExpression != null)
        {
            return html.EditorFor(expression, new { htmlAttributes = new { id = propertyExpression.Member.Name } });
        }
    }

    return EditorExtensions.EditorFor(html, expression);
}

You could even default the overrideId parameter to true to make all your existing usages work in place assuming you have the extension class in a namespace they're already using.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.