@teo van kotによると、MVCはデフォルトでこれを行います。しかし、プロパティへのパスがmodel.Submodel.PropertyNameのようなものであれば、ID属性は "Submodel_PropertyName"になります。あなただけの「PropertyName意味」をしたい場合は、この拡張メソッド/ラッパーを使用することができますかみそりビュー出力の
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、 @プレースホルダ= Html.DisplayNameFor(M => m.FirstName) })のよう
'? – Theo
@テオ、そうですね。 – idukic