Formatting strings in ASP.NET Razor

醉酒当歌 提交于 2019-12-23 07:56:19

问题


I am currently writing a small templating system in ASP.NET to allow users to add content. For example, the user can enter the string (variable type is string).

topHeader[x] = "They think it's all over. It is now!";

However, one change that's needed is the ability to add some basic HTML tags within this content, so the following can be done

topHeader[x] = "They think it's all over. <strong>It is now!</strong>";

or

topHeader[x] = "They think it's all over. <a title="Football News" href="URL">It is now!</a>";

If you add such things into strings now they are not formatted as HTML, but I want to somehow escape them so that they can be. Naturally I've looked on the Internet for the answer, but as Razor is fairly new there's not much out there to help me out.

Anyone have an idea of how to do this?


回答1:


You need to create an IHtmlString implementation holding your HTML source.

Razor plans to have a helper method to do this for you, but, AFAIK, it doesn't yet, so I believe you'll need to create your own class that implements the interface and returns your HTML from the GetHtmlString() method.
EDIT: You can use the HtmlString class.

You can either change your topHeader dictionary to hold IHtmlStrings instead of Strings, or you can leave your code as is, but wrap it in an HtmlString in the Razor view:

<tag>@new HtmlString(topHeader[x])</tag>

Make sure to correctly escape any non-HTML special characters.




回答2:


The helper method they added is called Html.Raw() and it is much cleaner.

Here is an example:

@Html.Raw("Hello <a>World</a>!")



回答3:


SLaks is right, but you don't need to write your own implementation of IHtmlString, there's one built in to System.Web called HtmlString. So:

topHeader[x] = new HtmlString("They think it's all over. <a title=\"Football News\" href=\"URL\">It is now!</a>");

Should do the trick.



来源:https://stackoverflow.com/questions/3341328/formatting-strings-in-asp-net-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!