2012-08-01 25 views
1

我需要更改我的模型的id屬性,因此我在TextBoxFor方法中從HTML helper分配新的id。但這顯然沒有在for屬性使用從HTML helper方法LabelFor時更改id在「Html.LabelFor」中更改屬性「for」

@Html.TextBoxFor(model => model.MyProperty, new { id = "CustomId" }) 

如何利用HTML helper方法LabelFor時,我可以改變for屬性?因爲此方法不允許更改屬性。

@Html.LabelFor(model => model.MyProperty) 

也許有一個屬性可以改變模型屬性中的id

感謝

編輯發表評論

我使用LabelFor,因爲我需要從DataAnnotationDescription取的名字:

[Display(Name = "Name of my property")] 
public string MyProperty { get; set; } 
+0

沒有理由使用'HTML。如果您不想將標籤與模型中的匹配字段綁定,請使用「Html.Label」來代替LabelFor。 – 2012-08-01 12:54:54

+0

@SteenT看到「編輯」,謝謝 – 2012-08-01 13:04:38

+0

爲什麼你需要在第一個地方設置ID? – 2012-08-01 13:13:31

回答

1

我想你需要創建自己的擴展那我已經做了一個需要html屬性的東西,你可以用它來解決你的問題:

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Object htmlAttributes) { 
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData); 
    String fieldname = ExpressionHelper.GetExpressionText(expression); 

    fieldname = metadata.DisplayName ?? metadata.PropertyName ?? fieldname.Split(new Char[] { '.' }).Last<String>(); 
    if (String.IsNullOrEmpty(fieldname)) { 
     return MvcHtmlString.Empty; 
    } 
    TagBuilder tagBuilder = new TagBuilder("label"); 
    tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldname))); 
    tagBuilder.SetInnerText(fieldname); 
    RouteValueDictionary attr = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); 
    tagBuilder.MergeAttributes<String, Object>(attr); 
    return tagBuilder.ToMvcHtmlString(); 
} 
+0

+1爲快速響應,我嘗試一下然後回答 – 2012-08-01 13:13:23

3

視圖模型:

public IEnumerable<SportingLisbon> SportingLisbonList { get; set; } 

查看:

@Html.LabelFor(model => model.SportingLisbonList, new { @for = "IdSportingLisbon" }) 

瀏覽器:
<標籤爲= 「IdSportingLisbon」 >里斯本競技< /標籤>

說明:
設置不同的屬性上LabelFor。


沒有新{@for = 「IdSportingLisbon」}
瀏覽器:用於= 「SportingLisbonList」 >里斯本< /標籤>



< 標籤

web.config:
<compilation debug="true" targetFramework="4.5" />

<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" /> 
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> 


+1

請正確格式化爲代碼示例。而一些描述性文字總是很好; o) – 2014-07-31 14:16:45

+0

希望它有幫助! ;) – user3895976 2014-08-01 11:58:29