在ASP.NET剃刀格式化字符串 [英] Formatting strings in ASP.NET Razor

查看:124
本文介绍了在ASP.NET剃刀格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!";

不过,这需要的一个改变是将这些内容中添加一些基本的HTML标签的能力,所以下面可以做

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>";

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

如果您添加这样的事情到字符串现在他们没有格式化为HTML,但我想以某种方式逃避他们,让他们可以。当然,我已经看了网上的答案,但因为剃刀是相当新的没有多少都来帮助我。

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?

推荐答案

您需要创建一个的 IHtmlString 实施牵着你的HTML源代码。

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

<击>剃刀计划有一个辅助的方法来为你做这个,但是,据我所知,这还没有,所以我相信你需要创建自己的类实现接口,并从返回的HTML在 GetHtmlString()方法。结果
修改:您可以使用 HtmlString

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.

您可以更改您的 topHeader 字典持有 IHtmlString 的S代替字符串 S,或者您也可以留下您的code原样,但在的Razor视图敷在一个 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:

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

请一定要正确逃生任何非HTML特殊字符。

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

这篇关于在ASP.NET剃刀格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆