简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM