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 comm开发者_开发知识库ents with <a href=\"http://daringfireball.net/projects/markdown/syntax\">Markdown</a>)")]
public string Body { get; set; }
Which results in the following display:
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?
I am afraid that you will have to do this manually. All HTML helpers simply HTML encode the content.
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.
精彩评论