所以我使用了
Twitter Bootstrap,我的大部分表单看起来都很棒
@H_404_2@<div class="control-group">
@Html.LabelFor(m => m.Prop)
<div class="controls">
@Html.EditorFor(m => m.Prop)
</div>
@Html.ValidationMessageFor(model => model.Prop)
</div>
唯一的问题是无线电按钮和复选框. Twitter Bootstrap调用HTML5样式标签,其中包含无线电或复选框输入内部的标签标签
@H_404_2@<label class="checkBox"> <input type="checkBox"> Check me out </label>如果我不能用@Html创建这些,或者重载,我至少可以使用Labelfor创建的文本?
@H_404_2@<label class="checkBox"> @Html.EditorFor(m=> m.Prop) @Html.TheVariableThatContainsTheTextThatLabelForUsesFor(m => m.Prop) </label>解决方法
为什么你不能用@Html创建这些.如果你编写自己的扩展方法(见下文),应该这样做吗?
@H_404_2@public static class HtmlHelperExtensions
{
public static MvcHtmlString MyCheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel,bool>> expression,object htmlLabelAttributes = null,object htmlCheckBoxAttributes = null)
{
var checkBox = htmlHelper.CheckBoxFor(expression,htmlCheckBoxAttributes);
var labelTag = new TagBuilder("label");
labelTag.AddCssClass("checkBox");
labelTag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlLabelAttributes));
labelTag.InnerHtml = checkBox.ToString();
return new MvcHtmlString(labelTag.ToString());
}
}
编辑:
这个修订版本怎么样这正是标签所做的.
@H_404_2@public static class HtmlHelperExtensions { public static MvcHtmlString MyCheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper,object htmlCheckBoxAttributes = null) { var checkBox = htmlHelper.CheckBoxFor(expression,htmlCheckBoxAttributes); var labelTag = new TagBuilder("label"); var checkBoxName = ExpressionHelper.GetExpressionText(expression); labelTag.AddCssClass("checkBox"); labelTag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlLabelAttributes)); labelTag.InnerHtml = checkBox.ToString() + LabelHelper(ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData),checkBoxName); return new MvcHtmlString(labelTag.ToString()); } private static MvcHtmlString LabelHelper(ModelMetadata Metadata,string fieldName) { string labelText; var displayName = Metadata.DisplayName; if (displayName == null) { var propertyName = Metadata.PropertyName; labelText = propertyName ?? fieldName.Split(new[] { '.' }).Last(); } else { labelText = displayName; } if (string.IsNullOrEmpty(labelText)) { return MvcHtmlString.Empty; } return new MvcHtmlString(labelText); } }我应该注意,使用MVC 4有一个DisplayNameFor Helper,所以整个标签业务可以简化一下.