2011-09-06 152 views
4

在剃刀我知道,如果你寫如何獲取表單名稱屬性

@Html.HiddenFor(x => x.PropertyX.PropertyY) 

它會生成HTML,如:

<input type="hidden" name="PropertyX.PropertyY" value="..."> 

和(特別是),如果這是一個編輯器它可能生成此HTML的模板:

<input type="hidden" name="ParentProperty[12].PropertyX.PropertyY" value="..."> 

如何獲取任意屬性的名稱?我猜想一定是有辦法做到這一點使用MVC架構

回答

7

你可以寫一個自定義的助手(也許還有一些方法或類?):

public static class NameExtensions 
{ 
    public static string NameFor<TModel, TProperty>(
     this HtmlHelper<TModel> html, 
     Expression<Func<TModel, TProperty>> expression 
    ) 
    { 
     var partialName = ExpressionHelper.GetExpressionText(expression); 
     return html 
      .ViewContext 
      .ViewData 
      .TemplateInfo 
      // You could do the same with GetFullHtmlFieldId 
      // if you were interested in the id of the element 
      .GetFullHtmlFieldName(partialName); 
    } 
} 

然後:

@Html.NameFor(x => x.PropertyX.PropertyY) 
+0

它並不完全遵循得墨忒耳的規律,但它讓我擺脫束縛。謝謝! – kelloti

+0

這真是太好了。 –

+3

這現在在MVC 4 [問題在這裏](http://stackoverflow.com/questions/3444021/htmlhelper-namefor-method)和[MSDN鏈接在這裏](http://msdn.microsoft.com/en -us /庫/ hh833703(v = vs.108)的.aspx) – Liam