如何将“Html.SomeHelper”属性值设置为等于模型属性名称?

时间:2016-10-20 16:57:19

标签: c# asp.net-mvc asp.net-core-mvc html-helper c#-6.0

我有表单模型,我想使用属性名作为某些表单字段属性的值。最好的方法是什么? (在这种情况下,我希望 id =“PropertyName”)。

// FormViewModel
[Display(Name = "First name*")]
[Required(ErrorMessage = "This field is required")]
public string FirstName { get; set; }

// Index.cshtml
<form id="form1" asp-controller="controller" asp-action="Index" method="post">
 <div class="form-group">
   @Html.TextBoxFor(m => m.FirstName, new
   {
     @id = "firstName",
     @placeholder = Html.DisplayNameFor(m => m.FirstName)
   })
   @Html.ValidationMessageFor(m => m.FirstName)
 </div>
</form>

TNX!

3 个答案:

答案 0 :(得分:1)

As @teo van kot said, MVC does that by default. But, if path to your property is something like model.Submodel.PropertyName, ID attribute will be "Submodel_PropertyName". If you want just "PropertyName", then this extension method/wrapper can be used:

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)  });
    }
}

in the razor view output will be like this:

@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="">

Problem with first and third approach, so using this technique, if you have same property name on several places in the model:

@Html.CustomTextBoxFor(x => x.DeliveryAddress.StreetName)
@Html.CustomTextBoxFor(x => x.BillingAddress.StreetName)

both input tags will have the same ID attribute!

Examples are written for MVC6, MVC5 uses different HtmlHelper types.

答案 1 :(得分:0)

你不应该逃避你的placeholder财产:

   @Html.TextBoxFor(m => m.FirstName, new
   {
     @id = "firstName",
     placeholder = Html.DisplayNameFor(m => m.FirstName)
   })

默认情况下,@id = "firstName"强类型助手不需要添加id属性和属性名称,所以在你的情况下它会是这样的:

   @Html.TextBoxFor(m => m.FirstName, new
   {
     placeholder = Html.DisplayNameFor(m => m.FirstName)
   })

答案 2 :(得分:0)

根据上面的内容,看起来你正在寻找的解决方案是

@Html.TextBoxFor(m => m.FirstName, 
new { @id = Model.FirstName, 
@placeholder = Html.DisplayNameFor(m => m.FirstName) 
})

但我说那里肯定有代码味道......这是一件非常奇怪的事情。