1

我正在使用:@Html.TextBoxFor(m => m.UserName)。这给了我:

<input data-val="true" 
       data-val-required="The User name field is required." 
       id="UserName" name="UserName" type="text" value="xxx">

我想要的是产生这样的<input>东西:

<input class="login1" name="UserName" 
       placeholder="Username (or guest)" required size="25" type="text">

有没有办法可以自定义 TextBoxFor 以添加占位符、必需和大小?

4

4 回答 4

3

是的,您需要添加另一个参数

@Html.TextBoxFor(m => m.UserName, new { placeholder="Username (or guest", ...}

另请参阅:具有特殊 html 属性的 Html Helper

于 2013-10-18T16:36:22.680 回答
2

您可以编写自己的助手:

public static class CustomHelpers
{
    public static MvcHtmlString CustomTexBoxFor<TModel, TProp>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProp>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        string name = ExpressionHelper.GetExpressionText(expression);

        TagBuilder tagBuilder = new TagBuilder("input");
        tagBuilder.MergeAttribute("name", name);
        tagBuilder.MergeAttribute("value", metadata.Model.ToString());
        tagBuilder.MergeAttribute("placeholder", "Username (or guest)");
        ... other attributes and htmlAttribute parameters

        return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));
    }
}
于 2013-10-18T17:03:25.790 回答
1

如果您不需要验证相关的属性,我认为您必须使用@Html.TextBox();

@Html.TextBox(Model.UserName.ToString(), Model.UserName, 
              new {@size ="25", @placeholder="Username (or guest)" ... })

@用作转义关键字(如@class)的前缀。不过,您可能不需要它作为占位符和大小。

于 2013-10-18T16:41:12.130 回答
1

删除模型验证以删除 data-val-required 属性并添加一些 html 属性,如下所示。

@Html.TextBoxFor(m => m.UserName,new {placeholder="Username (or guest)", 
required = "required ",@size="25" })
于 2013-10-18T18:19:45.233 回答