在ASP.NET Razor中格式化字符串

[英]Formatting strings in ASP.NET Razor


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).

我目前正在ASP.NET中编写一个小模板系统,以允许用户添加内容。例如,用户可以输入字符串(变量类型是字符串)。

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

但是,需要进行一项更改是在此内容中添加一些基本HTML标记的功能,因此可以执行以下操作

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.

如果你把这些东西添加到字符串中现在它们没有格式化为HTML,但我想以某种方式逃避它们以便它们可以。当然,我已经在互联网上寻找答案,但由于Razor相当新,所以没有太多可以帮助我。

Anyone have an idea of how to do this?

任何人都知道如何做到这一点?

3 个解决方案

#1


9  

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

您需要创建一个包含HTML源的IHtmlString实现。

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.

Razor计划有一个帮助方法为你做这个,但是,AFAIK,它还没有,所以我相信你需要创建自己的类来实现接口并从GetHtmlString()方法返回你的HTML。编辑:您可以使用HtmlString类。

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:

您可以更改topHeader字典以保存IHtmlStrings而不是字符串,或者您可以保留代码,但将其包装在Razor视图中的HtmlString中:

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

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

确保正确转义任何非HTML特殊字符。

#2


9  

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

他们添加的辅助方法称为Html.Raw(),它更清晰。

Here is an example:

这是一个例子:

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

#3


4  

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:

SLaks是正确的,但您不需要编写自己的IHtmlString实现,System.Web中内置了一个名为HtmlString的实现。所以:

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

Should do the trick.

应该做的伎俩。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2010/07/27/72031c23884dc01231ed38dca3d7531e.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告