Asp.net mvc 3 使用Html帮助器的Html内部标签

Asp.net mvc 3 使用Html帮助器的Html内部标签,asp.net-mvc-3,html-helper,Asp.net Mvc 3,Html Helper,如何在带有html.label的标签中添加内嵌html元素?您必须编写自己的帮助程序。内置的Html.Label帮助程序自动对labelText参数进行Html编码。对于自定义帮助程序来说似乎是一个不错的方案: public static class LabelExtensions { public static MvcHtmlString LabelFor<TModel, TProperty>( this HtmlHelper<TModel> h

如何在带有html.label的标签中添加内嵌html元素?

您必须编写自己的帮助程序。内置的
Html.Label
帮助程序自动对
labelText
参数进行Html编码。

对于自定义帮助程序来说似乎是一个不错的方案:

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());
    }
}
公共静态类标签扩展
{
公共静态MvcHtmlString LabelFor(
这个HtmlHelper HtmlHelper,
表达式ex,
Func模板
)
{
var htmlFieldName=ExpressionHelper.GetExpressionText(ex);
var for=htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
var标签=新标记生成器(“标签”);
label.Attributes[“for”]=TagBuilder.CreateSanitizedId(for);
label.InnerHtml=模板(null).ToHtmlString();
返回MvcHtmlString.Create(label.ToString());
}
}
然后:

@Html.LabelFor(
    x => x.Name, 
    @<span>Hello World</span>
)
@Html.LabelFor(
    x => x.Name, 
    @<em>mandatory</em>
)
@Html.LabelFor(
x=>x.Name,
@你好,世界
)

更新:

要实现您在评论部分提出的要求,您可以尝试以下方法:

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());
    }
}
公共静态类HtmlHelperExtensions
{
公共静态MvcHtmlString LabelFor(此HtmlHelper HtmlHelper、表达式ex、Func模板)
{
var htmlFieldName=ExpressionHelper.GetExpressionText(ex);
var propertyName=htmlFieldName.Split('.').Last();
var标签=新标记生成器(“标签”);
label.Attributes[“for”]=TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName));
label.InnerHtml=string.Format(
"{0} {1}", 
propertyName,
模板(null).ToHtmlString()
);
返回MvcHtmlString.Create(label.ToString());
}
}
然后:

@Html.LabelFor(
    x => x.Name, 
    @<span>Hello World</span>
)
@Html.LabelFor(
    x => x.Name, 
    @<em>mandatory</em>
)
@Html.LabelFor(
x=>x.Name,
@强制性的
)

我借用了达林的答案,并补充了它。我在标签文本之前添加了Html功能,在标签文本之后添加了Html功能。我还添加了一系列重载方法和注释

我也从这篇文章中得到了一些信息:

希望能帮助人们

namespace System.Web.Mvc.Html
{
    public static class LabelExtensions
    {
        /// <summary>Creates a Label with custom Html before the label text.  Only starting Html is provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml)
        {
            return LabelFor(html, expression, startHtml, null, new RouteValueDictionary("new {}"));
        }

        /// <summary>Creates a Label with custom Html before the label text.  Starting Html and a single Html attribute is provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="htmlAttributes">A single Html attribute to include.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, object htmlAttributes)
        {
            return LabelFor(html, expression, startHtml, null, new RouteValueDictionary(htmlAttributes));
        }

        /// <summary>Creates a Label with custom Html before the label text.  Starting Html and a collection of Html attributes are provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="htmlAttributes">A collection of Html attributes to include.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, Func<object, HelperResult> startHtml, IDictionary<string, object> htmlAttributes)
        {
            return LabelFor(html, expression, startHtml, null, htmlAttributes);
        }

        /// <summary>Creates a Label with custom Html before and after the label text.  Starting Html and ending Html are provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="endHtml">Html to follow the label text.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml)
        {
            return LabelFor(html, expression, startHtml, endHtml, new RouteValueDictionary("new {}"));
        }

        /// <summary>Creates a Label with custom Html before and after the label text.  Starting Html, ending Html, and a single Html attribute are provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="endHtml">Html to follow the label text.</param>
        /// <param name="htmlAttributes">A single Html attribute to include.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml, object htmlAttributes)
        {
            return LabelFor(html, expression, startHtml, endHtml, new RouteValueDictionary(htmlAttributes));
        }

        /// <summary>Creates a Label with custom Html before and after the label text.  Starting Html, ending Html, and a collection of Html attributes are provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="endHtml">Html to follow the label text.</param>
        /// <param name="htmlAttributes">A collection of Html attributes to include.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml, IDictionary<string, object> htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);

            //Use the DisplayName or PropertyName for the metadata if available.  Otherwise default to the htmlFieldName provided by the user.
            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }

            //Create the new label.
            TagBuilder tag = new TagBuilder("label");

            //Add the specified Html attributes
            tag.MergeAttributes(htmlAttributes);

            //Specify what property the label is tied to.
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

            //Run through the various iterations of null starting or ending Html text.
            if (startHtml == null && endHtml == null) tag.InnerHtml = labelText;
            else if (startHtml != null && endHtml == null) tag.InnerHtml = string.Format("{0}{1}", startHtml(null).ToHtmlString(), labelText);
            else if (startHtml == null && endHtml != null) tag.InnerHtml = string.Format("{0}{1}", labelText, endHtml(null).ToHtmlString());
            else tag.InnerHtml = string.Format("{0}{1}{2}", startHtml(null).ToHtmlString(), labelText, endHtml(null).ToHtmlString());

            return MvcHtmlString.Create(tag.ToString());
        }
    }
}
namespace System.Web.Mvc.Html
{
公共静态类标签扩展
{
///在标签文本之前使用自定义Html创建标签。仅提供起始Html。
///Html以抢占标签文本。
///标签的MVC Html
公共静态MvcHtmlString LabelFor(此HtmlHelper html、表达式、Func startHtml)
{
返回LabelFor(html,expression,startHtml,null,newroutevaluedictionary(“new{}”));
}
///在标签文本之前使用自定义Html创建标签。启动Html并提供单个Html属性。
///Html以抢占标签文本。
///要包含的单个Html属性。
///标签的MVC Html
公共静态MvcHtmlString LabelFor(此HtmlHelper html、表达式、Func startHtml、对象htmlAttributes)
{
返回LabelFor(html,expression,startHtml,null,newrouteValueDictionary(htmlAttributes));
}
///在标签文本之前使用自定义Html创建标签。提供了启动Html和Html属性集合。
///Html以抢占标签文本。
///要包含的Html属性的集合。
///标签的MVC Html
公共静态MvcHtmlString LabelFor(此HtmlHelper html、表达式、Func startHtml、IDictionary HtmlAttribute)
{
返回LabelFor(html,expression,startHtml,null,htmlAttributes);
}
///在标签文本前后使用自定义Html创建标签。提供起始Html和结束Html。
///Html以抢占标签文本。
///Html以跟随标签文本。
///标签的MVC Html
公共静态MvcHtmlString LabelFor(此HtmlHelper html、表达式表达式、Func startHtml、Func endHtml)
{
返回LabelFor(html,expression,startHtml,endHtml,newroutevaluedictionary(“new{}”));
}
///在标签文本前后使用自定义Html创建标签。提供起始Html、结束Html和单个Html属性。
///Html以抢占标签文本。
///Html以跟随标签文本。
///要包含的单个Html属性。
///标签的MVC Html
公共静态MvcHtmlString LabelFor(此HtmlHelper html、表达式表达式、Func startHtml、Func endHtml、对象htmlAttributes)
{
返回LabelFor(html、expression、startHtml、endHtml、newroutevaluedictionary(htmlAttributes));
}
///在标签文本前后使用自定义Html创建标签。提供起始Html、结束Html和Html属性集合。
///Html以抢占标签文本。
///Html以跟随标签文本。
///要包含的Html属性的集合。
///标签的MVC Html
公共静态MvcHtmlString LabelFor(此HtmlHelper html、表达式表达式、Func startHtml、Func endHtml、IDictionary HtmlatAttribute)
{
ModelMetadata=ModelMetadata.FromLambdaExpression(表达式,html.ViewData);
字符串htmlFieldName=ExpressionHelper.GetExpressionText(表达式);
//如果元数据可用,请使用DisplayName或PropertyName。否则,默认为用户提供的htmlFieldName。
字符串labelText=metadata.DisplayName??metadata.PropertyName??htmlFieldName.Split('.').Last();
if(String.IsNullOrEmpty(labelText))
{
返回MvcHtmlString.Empty;
}
//创建新标签。
标记生成器标记=新标记生成器(“标签”);
//添加指定的Html属性
合并属性(htmlAttributes);
//指定所需的属性
[Display(Name ="Phone",Description = "should be included extention")]
public string Phone { get; set; }
@using yourNamespace
@{ MvcHtmlString label = Html.LabelFor(m => m.ModelProperty, "<span class='cssClass'>Label HTML</span>", new { @class = "clabel"}); }
@Html.Raw(HttpUtility.HtmlDecode(label.ToString()))