Brian Denomey
Brian Denomey

Reputation: 176

@Html.LabelFor with an <a> tag inside it

This should be a fairly simple question, all I want to do is use @Html.LabelFor within a razor view. One of my labels is different, it has an <a> tag in it. the problem is when I use LabelFor, it encodes the html as & lt;. I've tried a lot of different approaches to making this happen but none of them are working. Here's the code.

@Html.LabelFor(model => model.Question, new { @for = "Question" })

what should get outputted:

<label for="question"><a href=\"mailto:[email protected]">[email protected]</a></label>

what does get outputted:

&lt;label for="question"&gt;&lt;a href=\"mailto:[email protected]"&gt;[email protected]&lt;/a&gt;</label>

(my < have been replaced with & lt ; without the spaces, thus the code shows on the page instead of rendering as a link)

how can I make it output what it should?

note, model.Question is set to <a href="mailto:[email protected]">[email protected]</a>

Upvotes: 1

Views: 4814

Answers (2)

DDan
DDan

Reputation: 8276

Why do you want your label to contain the full HTML? I think it would be a better approach to store email address, and in your view you could do:

 <a href="mailto:@Model.Email">@Model.Email</a>

To get the expected result.

EDIT

IMO by encoding things in label is just going to make your work more complicated as labels are not meant to hold formatted HTML or feature or anything like that, merely a caption to display. Example usage:

Model code:

[Display(Name = "Email address")]
public string EmailAddress { get; set; }

In view:

@Html.LabelFor(model => model.EmailAddress): 
@Html.DisplayFor(model => model.EmailAddress)

<!-- OR (no label element just the label text)-->

@Html.DisplayNameFor(model => model.EmailAddress): 
@Html.DisplayFor(model => model.EmailAddress)

Then can be combined in any way:

[Display(Name = "Send Email")]
public string EmailAddress { get; set; }

And

@Html.LabelFor(model => model.EmailAddress): <a href="mailto:@Model.EmailAddress">@Model.Email</a>

In runtime will be:

Send Email: [email protected]

Upvotes: 0

rism
rism

Reputation: 12142

You're fighting the Razor system since it encodes by default. That's the beauty of using Razor. Many of the tag classes including Labelwill ultimately render themselves by calling TagBuilderExtensions.ToMvcHtmlString

internal static class TagBuilderExtensions
  {
    internal static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)
    {
      return new MvcHtmlString(tagBuilder.ToString(renderMode));
    }
  }

MvcHtmlString represents an HTML-encoded string that should not be encoded again. So you can't do what you're trying to do via LabelFor. Razor is in fact specifically ensuring that you can't.

But since your malto: is not really a label anyway you can just:

@Html.Raw(Server.HtmlDecode(Model.MyField)

Upvotes: 0

Related Questions