使用Html助手的Html里面的标签

问题描述 投票:9回答:5

如何使用Html.Label在标签内添加内联html元素?

asp.net-mvc-3 html-helper
5个回答
20
投票

看起来像自定义助手的好方案:

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>
)

更新:

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

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>
)

2
投票

你必须写自己的帮手。内置的Html.Label助手自动对labelText参数进行HTML编码。


2
投票

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

我也从这篇文章中得到了一些信息:How can I override the @Html.LabelFor template?

希望如果有帮助的人。

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());
        }
    }
}

1
投票

为了满足SOC和Solid原则,可以将代码增强到以下代码:

  public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex,bool applyStylingHtml)
    {
        var metadata = ModelMetadata.FromLambdaExpression(ex, htmlHelper.ViewData);
        string displayName = metadata.DisplayName;
        string description= metadata.Description;
        if (String.IsNullOrEmpty(displayName))
        {
            return MvcHtmlString.Empty;
        }

        var sb = new StringBuilder();
        sb.Append(displayName);


        var htmlFieldName = ExpressionHelper.GetExpressionText(ex);
        var propertyName = htmlFieldName.Split('.').Last();

        var tag = new TagBuilder("label");
        tag.Attributes["for"] = TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName));
        tag.SetInnerText(sb.ToString());

        //Func<object, HelperResult> template='<em>';
        HtmlString nestedHtml=new HtmlString("<em>"+description+"</em>");
        tag.InnerHtml = string.Format(
            "{0} {1}",
            tag.InnerHtml,
           nestedHtml
        );

        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }

然后在Razor代码中使用它:

@Html.LabelFor(m => m.Phone,true)

为了使一切更加动态,描述属性应该应用于Model类,然后HtmlHelper将获取描述作为要应用的文本“em”Html标记:

[Display(Name ="Phone",Description = "should be included extention")]
public string Phone { get; set; }

通过添加以下内容,您需要将自定义的HtmlHelper命名空间导入到视图中:

@using yourNamespace

1
投票

而不是编写扩展方法,您可以使用以下剃刀代码:

@{ MvcHtmlString label = Html.LabelFor(m => m.ModelProperty, "<span class='cssClass'>Label HTML</span>", new { @class = "clabel"}); }
@Html.Raw(HttpUtility.HtmlDecode(label.ToString()))
© www.soinside.com 2019 - 2024. All rights reserved.