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

應該做的伎倆。


注意!

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



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