正如@teo van kot所說,MVC默認是這樣做的。但是,如果您的屬性路徑是類似於model.Submodel.PropertyName,ID屬性將是「Submodel_PropertyName」。如果你只想「屬性名」,然後就可以使用該擴展方法/包裝:在Razor視圖輸出
public static class Extension method
{
public static IHtmlContent CustomTextBoxFor<TModel, TResult>(this IHtmlHelper<TModel> helper, Expression<Func<TModel, TResult>> expression)
{
// very simple implementation, can fail if expression is not as expected!
var body = expression.Body as MemberExpression;
if(body == null) throw new Exception("Expression refers to a method, not a property");
return helper.TextBoxFor(expression, null, new { id = body.Member.Name, placeholder = helper.DisplayNameFor(expression) });
}
}
將是這樣的:
@Html.CustomTextBoxFor(x => x.Foo)
<input id="Foo" name="Foo" type="text" placeholder="Foo" value="">
@Html.TextBoxFor(x => x.Foo)
<input id="Foo" name="Foo" type="text" value="">
@Html.CustomTextBoxFor(x => x.AnotherModel.Foo)
<input id="Foo" name="AnotherModel.Foo" type="text" placeholder="Foo" value="">
@Html.TextBoxFor(x => x.AnotherModel.Foo)
<input id="AnotherModel_Foo" name="AnotherModel.Foo" type="text" value="">
問題的第一和第三種方法,所以使用這種方法,如果您對模型中的幾個地方有相同的屬性名稱:
@Html.CustomTextBoxFor(x => x.DeliveryAddress.StreetName)
@Html.CustomTextBoxFor(x => x.BillingAddress.StreetName)
兩個輸入標籤將具有相同的ID屬性!
示例是針對MVC6編寫的,MVC5使用不同的HtmlHelper類型。
如在'@ Html.TextBoxFor(M => m.FirstName,新 { @id = Model.FirstName, @placeholder = Html.DisplayNameFor(M => m.FirstName) })'? – Theo
@Theo,是的,就是這樣。 – idukic