我发现自己重复这种代码块太频繁?
<div class="form-group">
<div class="col-sm-3 control-label">
@Html.LabelFor(m => m.Name)
</div>
<div class="col-sm-9">
@Html.TextBoxFor(m => m.Name, null, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Name)
</div>
</div>
我一直在试图建立一个MvcHtmlString自定义扩展,但它假定@ Html.LabelFor命令是文本,这是显示的内容。
编辑:感谢乔和斯蒂芬! 这就是我失踪了。
下面是我的代码块最终的答案
static MvcHtmlString BaseFieldFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, string>> expression, MvcHtmlString innerHtml, string style = null) {
var labelDiv = new TagBuilder("div");
labelDiv.AddCssClass("col-sm-3 control-label");
labelDiv.InnerHtml += helper.LabelFor(expression, new {
htmlAttributes = new { @class = "form-control" }
});
var textDiv = new TagBuilder("div");
textDiv.AddCssClass("col-md-9");
textDiv.InnerHtml += innerHtml;
textDiv.InnerHtml += helper.ValidationMessageFor(expression);
var groupDiv = new TagBuilder("div");
groupDiv.AddCssClass("form-group");
groupDiv.InnerHtml += labelDiv;
groupDiv.InnerHtml += textDiv;
return new MvcHtmlString(groupDiv.ToString(TagRenderMode.Normal));
}
和使用
public static MvcHtmlString FieldFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, string>> expression, string style = null) {
var innerHtml = helper.TextBoxFor(expression, null, new { @class = "form-control", style });
return BaseFieldFor(helper, expression, innerHtml, style);
}
public static MvcHtmlString DropDownListFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, string>> expression, IEnumerable<SelectListItem> list, string style = null){
var innerHtml = helper.DropDownListFor(expression, new SelectList(list, "Value", "Text"), new { @class = "form-control", style });
return BaseFieldFor(helper, expression, innerHtml, style);
}
现在,我可以简单地使用它!
<div class="panel-body form-horizontal">
@Html.FieldFor(m => m.Name)
@Html.FieldFor(m => m.Address1)
@Html.FieldFor(m => m.Address2)
@Html.FieldFor(m => m.City)
@Html.DropDownListFor(m => m.State, AllowableValues.StateList, "max-width: 200px;")
@Html.FieldFor(m => m.PostalCode, "max-width: 150px;")
@Html.FieldFor(m => m.Phone, "max-width: 150px;")
</div>