Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render an HTML link within a form label using a DisplayName attribute and/or LabelFor?

I have a comment form where I am trying to render an HTML link to the Markdown reference within an HTML label. I tried adding the link to the DisplayName attribute in my view model:

[DisplayName("Comment (you can format comments with <a href=\"http://daringfireball.net/projects/markdown/syntax\">Markdown</a>)")]
public string Body { get; set; }

Which results in the following display: Comment Body Field

I also tried adding the label directly within the view:

@Html.LabelFor(x => x.Comment.Body, "Comment (you can format comments with <a href=\"http://daringfireball.net/projects/markdown/syntax\">Markdown</a>)") 

But the result is understandably the same.

I realise this is because MVC is HTMLEncoding the output for safety, but is there any way to turn this off per label, or do I just have to manually write out an HTML label in my view in this case?

like image 734
Mark Bell Avatar asked Oct 19 '25 14:10

Mark Bell


2 Answers

I am afraid that you will have to do this manually. All HTML helpers simply HTML encode the content.

like image 74
Darin Dimitrov Avatar answered Oct 22 '25 04:10

Darin Dimitrov


After a 8 year gap, I encountered this problem and you can in fact use a workaround to get this working.

Change the code in your model to this:

[Display(Name = "Comment (you can format comments with <a href=\"http://daringfireball.net/projects/markdown/syntax\">Markdown</a>)")]
public string Body { get; set; }

Add this into your view:

@Html.Raw(HttpUtility.HtmlDecode(@Html.LabelFor(m => m.Body).ToString()))

Here is a fiddle to see it.

like image 37
Tiberiuscan Avatar answered Oct 22 '25 05:10

Tiberiuscan