使用 Html 帮助程序的标签内的 Html [英] Html inside label using Html helper
本文介绍了使用 Html 帮助程序的标签内的 Html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 Html.Label 在标签内添加内联 html 元素?
How can I add inline html elements inside a label with Html.Label?
推荐答案
对于自定义帮助程序来说似乎是一个不错的方案:
Looks like a good scenario for a custom helper:
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> ex,
Func<object, HelperResult> template
)
{
var htmlFieldName = ExpressionHelper.GetExpressionText(ex);
var for = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
var label = new TagBuilder("label");
label.Attributes["for"] = TagBuilder.CreateSanitizedId(for);
label.InnerHtml = template(null).ToHtmlString();
return MvcHtmlString.Create(label.ToString());
}
}
然后:
@Html.LabelFor(
x => x.Name,
@<span>Hello World</span>
)
<小时>
更新:
要实现您在评论部分提出的要求,您可以尝试以下操作:
To achieve what you asked in the comments section you may try the following:
public static class HtmlHelperExtensions
{
public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex, Func<object, HelperResult> template)
{
var htmlFieldName = ExpressionHelper.GetExpressionText(ex);
var propertyName = htmlFieldName.Split('.').Last();
var label = new TagBuilder("label");
label.Attributes["for"] = TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName));
label.InnerHtml = string.Format(
"{0} {1}",
propertyName,
template(null).ToHtmlString()
);
return MvcHtmlString.Create(label.ToString());
}
}
然后:
@Html.LabelFor(
x => x.Name,
@<em>mandatory</em>
)
这篇关于使用 Html 帮助程序的标签内的 Html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文