简体   繁体   中英

Unescape the escape character in string before rendering

I want to display string enclosed with double quotes (eg "ABC") in text box. Currently it is not displaying since double quotes are being escaped. It is problem only with escaping the double quotes.

Eg

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

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

I want to avoid using regex or replace method to solve this.

Is there any method available in C# to solve this.

You have to do this:

<input id="txtCountryName" type="text" value="<%= Server.HtmlEncode(countryName) %>" />

Explanation

The problem is that your final HTML is being rendered like that:

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

You have to call Server.HtmlEncode to encode the " in HTML.

No, actually, they aren't being escaped.

To escape them, or rather encode them into their HTML entities, use HtmlEncode() :

<input id="txtCountryName" type="text" value="<%=Server.HtmlEncode(countryName)%>" />

On ASP.NET 4 you can use a different set of delimiters <%: %> for automatic escaping:

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

<input> is not a server control, so your example just performs string replacement. This yields a result of

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

which does not show what you want.

An elegant solution is to use a server control instead and to make ASP.NET set the property instead of just doing string replacement in HTML. That way, ASP.NET takes care of the escaping issues.

Step 1: Make your input control a server control. You do that by adding runat="server" .

Step 2: Use data binding syntax ( <%#... %> ).

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

Step 3: Perform data binding in codebehind:

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

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

Voilà, the text box shows "ABC" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM