Tag HTML in Helper Razor

Asked

Viewed 97 times

1

I have HTML code:

<label class="labelinput">Nº Compra<em>*</em></label>

Passing to the Helper was as follows:

@Html.Label("Nº Compra:", new {@class = "labelinput"})

But I couldn’t add the tag <em> with the Helper.

How I add the tag <em> to get together with the Helper string?

2 answers

0

Man, you just do it like this:

<em>
  @Html.Label("Nº Compra:", new {@class = "labelinput"})
</em>

0

According to this answer from Darin Dmitrov, implement the following extension (modified to reflect your scenario):

namespace MeuProjeto.Extensions
{
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString Label(this HtmlHelper<TModel> htmlHelper, String ex, Func<object, HelperResult> template, object htmlAttributes)
        {
            var label = new TagBuilder("label");
            label.MergeAttributes(htmlAttributes);
            label.InnerHtml = string.Format(
                "{0} {1}", 
                ex,
                template(null).ToHtmlString()
            );
            return MvcHtmlString.Create(label.ToString());
        }
    }
}

Use:

@Html.Label("Nº Compra",
    @"<em>*</em>",
    new { @class = "labelinput" }
)

A tip: register the namespace of its extensions in the web.config which is inside the directory Views:

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        ...
        <add namespace="MeuProjeto.Extensions" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.