简体   繁体   中英

ASP.NET Auto Escaping Characters?

I'm working with the following code that is contained in a.ASPX.CS page...

img = "<img src=\"" + yellow + "\" align=\"middle\" onclick=\"alert('You are the current high bidder but the auction's minimum bid reserve has not been met. You need to increase your max bid until the reserve has been met to have a chance in winning this domain auction.');return false;\" class=\"sBtnImg\" alt=\"\" />";

It gets written to a.ASPX page within a asp:repeater using the following...

<%# getAuctionFlag(Eval("AuctionAmt").ToString(), Eval("WinningBid").ToString(), Eval("UserMaxBid").ToString(), Eval("AuctionTypeDesc").ToString(), "", Eval("BidStatus").ToString())%>

The problem I am having is that the alert contains a single quote within auction's and all my attempts to escape it have failed. I tried \' and ' but .NET escapes it before it gets rendered as HTML. So I end up with...

onclick="alert('TEXTHERE' TEXTHERE');return false;"

A single backslash-quote gets interpreted (back to single-quote) at the C# string literal syntax level. You need to get a \' sequence through to the HTML level, which means as a string literal you would have to use \\' .

The better long-term answer is to stop nesting your string contexts. When you've got JavaScript code inside HTML markup inside a C# string literal, that's multiple levels of escaping you have to think about at once, and humans aren't good at doing that. Break the escaping down a level at a time, use alternative quotes where available, and put data in attributes instead of code where you can:

string warning= (
    "You are the current high bidder but the auction's minimum bid reserve "+
    "has not been met. You need to increase your max bid until the reserve "+
    "the reserve has been met to have a chance in winning this domain auction."
);

string html= String.Format(
    "<img src='{0}' class='sBtnImg' title='{1}' onclick='alert(this.title);'/>",
    HttpUtility.HtmlEncode(yellow),
    HttpUtility.HtmlEncode(warning)
);

Better still, omit onclick and use unobtrusive JavaScript to catch clicks and add behaviour dependent on the class . Then the warning text can be a static string in a.js file.

\' gets interpreted by C# exactly the same as ' . In order to include a literal backslash in the results, you need to escape the backslash itself:

" ... auction\\'s ..."

Have you tried double forwardslash? \'

Or you can try replacing the apostrophe with it's HTML code &apos;

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