asp.net-mvc 如何获取asp.net MVC EditorFor生成的HTML id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4829193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:49:00  来源:igfitidea点击:

How to get the HTML id generated by asp.net MVC EditorFor

asp.net-mvcasp.net-mvc-2

提问by LeftyX

I use the HTML Helpers to render my fields:

我使用 HTML Helpers 来呈现我的字段:

<%=Html.EditorFor(m => m.User.Surname)%>

and the output would be something like this:

输出将是这样的:

<input class="text-box single-line" id="User_Surname" 
          name="User.Surname" type="text" value="" />

The helper uses the className + '.' è fieldName to build the id.
I need to pass the id to a jQuery function. Is there a way to have it without hardcoding it? Maybe an helper which can use the ASP.NET MVC2 conventions?

帮助程序使用 className + '.' è fieldName 来构建 id。
我需要将 id 传递给 jQuery 函数。有没有办法在没有硬编码的情况下拥有它?也许是一个可以使用 ASP.NET MVC2 约定的助手?

采纳答案by LeftyX

I've followed the instructions of Mac's answer hereand I've built my own custom extension:

我已按照此处Mac 的回答说明进行操作,并构建了自己的自定义扩展:

public static class HtmlHelperExtensions
{
    public static string HtmlIdNameFor<TModel, TValue>(
        this HtmlHelper<TModel> htmlHelper,
        System.Linq.Expressions.Expression<Func<TModel, TValue>> expression)
    {
        return (GetHtmlIdNameFor(expression));
    }

    private static string GetHtmlIdNameFor<TModel, TValue>(Expression<Func<TModel, TValue>> expression)
    {
        if (expression.Body.NodeType == ExpressionType.Call)
        {
            var methodCallExpression = (MethodCallExpression)expression.Body;
            string name = GetHtmlIdNameFor(methodCallExpression);
            return name.Substring(expression.Parameters[0].Name.Length + 1).Replace('.', '_');

        }
        return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1).Replace('.', '_');
    }

    private static string GetHtmlIdNameFor(MethodCallExpression expression)
    {
        var methodCallExpression = expression.Object as MethodCallExpression;
        if (methodCallExpression != null)
        {
            return GetHtmlIdNameFor(methodCallExpression);
        }
        return expression.Object.ToString();
    }
}

I've imported my application's namespace

我已经导入了我的应用程序的命名空间

<%@ Import Namespace="MvcApplication2" %>

and finally I can use my code like this:

最后我可以像这样使用我的代码:

<%=Html.HtmlIdNameFor(m=>m.Customer.Name)%>

回答by bkaid

ASP.NET MVC 4 has Html.IdFor()built in that can return this:

ASP.NET MVC 4内置了Html.IdFor()可以返回:

@Html.IdFor(m => m.User.Surname)

回答by John Landheer

See this question: get the generated clientid for a form field, this is my answer:

请参阅此问题:获取为表单字段生成的 clientid,这是我的答案:

I use this helper:

我使用这个帮手:

public static partial class HtmlExtensions
{
    public static MvcHtmlString ClientIdFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression)
    {
        return MvcHtmlString.Create(
              htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(
                  ExpressionHelper.GetExpressionText(expression)));
    }
}

Use it just as you would any other helper: @Html.ClientIdFor(model=>model.client.email)

像使用任何其他助手一样使用它: @Html.ClientIdFor(model=>model.client.email)

回答by hunter

unless you create your own User.Surname EditorTemplate which you pass in some HTML attributes you won't be able to do this with EditorFor

除非您创建自己的 User.Surname EditorTemplate 并传入一些 HTML 属性,否则您将无法使用 EditorFor

However you can use TextBoxForand set the id

但是您可以使用TextBoxFor和设置 id

<%= Html.TextBoxFor(m => m.User.Surname, new { id = "myNewId" })%>


On the topic of retrieving this element with a jQuery selector you can achieve this without having to hardcode by using some of the ends-with selector. Using that you could probably still use EditorForand just select it with $("[id^='Surname]")`. If you're trying to select this specific element there's really no way to NOT hardcode SOMETHING in your jQuery code.

关于使用 jQuery 选择器检索此元素的主题,您可以通过使用某些带有选择器结尾来实现这一点,而无需进行硬编码。使用它,您可能仍然可以使用EditorFor,只需使用$("[id^='Surname]")`选择它。如果您尝试选择此特定元素,则真的没有办法不在您的 jQuery 代码中硬编码某些内容。