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

前端 未结 4 1841
无人共我
无人共我 2020-12-08 01:55

I use the HTML Helpers to render my fields:

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

and the output would be something like this:<

4条回答
  •  感情败类
    2020-12-08 02:14

    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(
            this HtmlHelper htmlHelper,
            System.Linq.Expressions.Expression> expression)
        {
            return (GetHtmlIdNameFor(expression));
        }
    
        private static string GetHtmlIdNameFor(Expression> 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)%>
    

提交回复
热议问题