我正在使用:@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来添加占位符,必需和大小?
答案 0 :(得分:3)
是的,您需要添加另一个参数
@Html.TextBoxFor(m => m.UserName, new { placeholder="Username (or guest", ...}
答案 1 :(得分: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));
}
}
答案 2 :(得分:1)
如果您不需要与验证相关的属性,我认为您必须使用@Html.TextBox()
;
@Html.TextBox(Model.UserName.ToString(), Model.UserName,
new {@size ="25", @placeholder="Username (or guest)" ... })
@
用作转义关键字(例如@class)的前缀。你可能不需要占位符和大小。
答案 3 :(得分:1)
删除模型验证以删除data-val-required属性并添加一些html属性,如下所示。
@Html.TextBoxFor(m => m.UserName,new {placeholder="Username (or guest)",
required = "required ",@size="25" })