里面的html标签使用HTML帮手 [英] Html inside label using Html helper

查看:239
本文介绍了里面的html标签使用HTML帮手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何添加内嵌HTML元素的标签里面加上Html.Label?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆