I followed the Mac answer instructions here , and I created 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 imported the application namespace
<%@ Import Namespace="MvcApplication2" %>
and finally, I can use my code as follows:
<%=Html.HtmlIdNameFor(m=>m.Customer.Name)%>
LeftyX Jan 29 '11 at 3:19 2011-01-29 15:19
source share