在渲染字符串之前,需要对字符串中的转义字符进行反转义。

3

我希望在文本框中显示用双引号(例如"ABC")括起来的字符串。目前这个字符串无法显示,因为双引号被转义了。这只是由于双引号被转义所导致的问题。

例如:

public const string countryName = "\"ABC\"";

<input id="txtCountryName" type="text" value="<%= countryName %>" />

我希望能够避免使用正则表达式或替换方法来解决这个问题。

在C#中是否有可用的方法来解决这个问题。


也许你的意思是在显示时要删除双引号? - BlackJack
3个回答

3
你需要这样做:
<input id="txtCountryName" type="text" value="<%= Server.HtmlEncode(countryName) %>" />

解释

问题在于你的最终HTML呈现出来的样子是这样的:

<input id="txtCountryName" type="text" value=""ABC"" />

您需要调用Server.HtmlEncode来编码HTML中的"

2
不,实际上它们没有被转义。
要转义它们,或者说将它们编码为HTML实体,请使用HtmlEncode()函数:
<input id="txtCountryName" type="text" value="<%=Server.HtmlEncode(countryName)%>" />

在ASP.NET 4中,您可以使用不同的分隔符<%: %>进行自动转义:
<input id="txtCountryName" type="text" value="<%:countryName%>" />

@Adrian:在ASP.NET中,它也是HttpServerUtility.HtmlEncode()的别名。 - BoltClock
没错。但是我在你之前几秒钟就已经发布了 :) - Adriano Carneiro

1

<input> 不是服务器控件,所以您的示例只执行字符串替换。这将产生以下结果:

<input id="txtCountryName" type="text" value=""ABC"" />

这并不展示你想要的。

一个优雅的解决方案是使用服务器控件,而不是仅在 HTML 中进行字符串替换,让 ASP.NET 设置属性。这样,ASP.NET 就会处理转义问题。

步骤 1:将输入控件变成服务器控件。通过添加 runat="server" 来实现。

步骤 2:使用数据绑定语法 (<%# ... %>)。

<input id="txtCountryName" type="text" runat="server" value="<%# countryName %>" />    

步骤三:在代码后端执行数据绑定:

public const string countryName = "\"ABC\"";

protected void Page_Load(object sender, EventArgs e)
{
    this.DataBind();
}

看这里,文本框显示着"ABC"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接