如何通过asp.net MVC EditorFor获取生成的HTML ID [英] How to get the HTML id generated by asp.net MVC EditorFor

查看:129
本文介绍了如何通过asp.net MVC EditorFor获取生成的HTML ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HTML助手来呈现我的字段:

I use the HTML Helpers to render my fields:

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

和输出将会是这样的:

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

助手使用的className +。 è字段名来构建ID。结果
我需要的ID传递给jQuery函数。有没有办法把它没有硬编码呢?
也许一个帮手,可以使用ASP.NET MVC2约定?

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?

推荐答案

我已经按照Mac的答案的指示<一个href=\"http://stackoverflow.com/questions/2512809/has-anyone-implement-radiobuttonlistfort-for-asp-net-mvc\">here我已经建立了自己的自定义扩展:

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

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" %>

终于我可以用我的code是这样的:

and finally I can use my code like this:

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

这篇关于如何通过asp.net MVC EditorFor获取生成的HTML ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆