【发布时间】:2013-07-24 01:29:26
【问题描述】:
我希望有人有一些想法。我想整理我的代码,所以我已经使用了 Html.LabelFor。但是现在我想为标签分配一个 CSS 类。
Html.LabelFor(model => model.Customer.Description ????)
有没有人知道这在 MVC3 中是否可行。请注意,我使用的是 MVC3。我已经看到了一篇关于 MVC2 的帖子,并且没有简单的解决方案。
【问题讨论】:
我希望有人有一些想法。我想整理我的代码,所以我已经使用了 Html.LabelFor。但是现在我想为标签分配一个 CSS 类。
Html.LabelFor(model => model.Customer.Description ????)
有没有人知道这在 MVC3 中是否可行。请注意,我使用的是 MVC3。我已经看到了一篇关于 MVC2 的帖子,并且没有简单的解决方案。
【问题讨论】:
给你,伙计-o:
namespace System.Web.Mvc.Html
{
using System;
using Collections.Generic;
using Linq;
using Linq.Expressions;
using Mvc;
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return html.LabelFor(expression, null, htmlAttributes);
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes)
{
return html.LabelHelper(
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression),
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),
labelText);
}
private static MvcHtmlString LabelHelper(this HtmlHelper html, ModelMetadata metadata, string htmlFieldName, IDictionary<string, object> htmlAttributes, string labelText = null)
{
var str = labelText
?? (metadata.DisplayName
?? (metadata.PropertyName
?? htmlFieldName.Split(new[] { '.' }).Last()));
if (string.IsNullOrEmpty(str))
return MvcHtmlString.Empty;
var tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tagBuilder.SetInnerText(str);
return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}
private static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)
{
return new MvcHtmlString(tagBuilder.ToString(renderMode));
}
}
}
【讨论】:
在 MVC 3 中没有内置的方法来执行此操作。您必须编写执行此操作的帮助程序。看看LabelExtensions 类,看看它是如何完成的。
【讨论】:
htmlAttributes 参数。也许有些疏忽。我会提交一个错误以确保我们在下一个版本中添加它。
htmlAttributes 参数,就像所有其他帮助程序一样,以启用此方案。不过,我们可能不会公开 LabelHelper 函数。但我希望这能满足您的需求。