我发现自己经常重复这个代码块.
<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>发布于 2014-11-20 22:35:14
您的助手需要使用内置的助手方法来生成html。例如
MvcHtmlString label = LabelExtensions.LabelFor(helper, expression});Refer this example,用于创建一个输出类似html的助手,包括标签、文本框和验证消息。
发布于 2014-11-20 22:14:06
您无法以尝试这样做的方式调用HTML帮助程序。它所要做的就是把它当作文本输出,正如您已经看到的结果。
相反,您需要引用HTML助手,如下所示:
string yourString = "Your string " + helper.LabelFor("text", "actionName");https://stackoverflow.com/questions/27046267
复制相似问题