为什么不能用@Html 创建这些。如果您编写自己的扩展方法(见下文),应该这样做,不是吗?
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());
}
}
编辑:
这个修订版怎么样。这完全复制了标签的作用。
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");
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,因此可以稍微简化整个标签业务。