有没有一种方法可以在不使用我的模型中的DisplayNameAttribute的情况下使用LabelFor助手和自定义标签文本?
发布于 2010-01-23 17:50:58
我已经为我的项目创建了这个html助手:
public static class MyLabelExtensions
{
public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText)
{
return Label(htmlHelper, forName, labelText, (object) null);
}
public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText,
object htmlAttributes)
{
return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText,
IDictionary<string, object> htmlAttributes)
{
var tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("for", forName.Replace(".", tagBuilder.IdAttributeDotReplacement), true);
tagBuilder.SetInnerText(labelText);
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string labelText)
{
return LabelFor(htmlHelper, expression, labelText, (object) null);
}
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string labelText, object htmlAttributes)
{
return LabelFor(htmlHelper, expression, labelText, new RouteValueDictionary(htmlAttributes));
}
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string labelText,
IDictionary<string, object> htmlAttributes)
{
string inputName = ExpressionHelper.GetExpressionText(expression);
return htmlHelper.Label(inputName, labelText, htmlAttributes);
}
}
我将它们与“强类型”资源一起使用:
<%= Html.LabelFor(m=>m.NickName, UserStrings.NickName) %>
希望这能帮上忙。
发布于 2010-11-11 08:45:36
MVC3 RC中有一个新的LabelFor重载,允许您指定labelText。
发布于 2010-01-16 10:13:42
为什么不创建你自己的Html Helper呢?
public static class MVCHelpers
{
public static string CustomLabelFor(this HtmlHelper helper, string ...)
{
return "<label ... </label>"
}
}
https://stackoverflow.com/questions/2075493
复制相似问题