开发者

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:

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜