2011-08-16 56 views
1

我與被包含在.ASPX.CS頁面下面的代碼工作...ASP.NET自動轉義字符?

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=\"\" />"; 

它被寫入到.aspx頁面中一個ASP中:中繼器使用以下...

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

我遇到的問題是警報在拍賣中包含單引號,並且我所有嘗試轉義它都失敗了。我試過\'和',但.NET在它被呈現爲HTML之前轉義它。所以我結束了......

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

回答

1

一個反斜槓引號被解釋在C#字符串文本語法水平(回單引號)。你需要得到一個\'序列到HTML級別,這意味着作爲一個字符串文字,你將不得不使用\\'

更好的長期答案是停止嵌套您的字符串上下文。當您在C#字符串文字中的HTML標記內部獲得JavaScript代碼時,您需要立即思考多個級別的轉義,而人類不擅長這樣做。打破在同一時間逸出下降一個等級,如果可以使用替代的報價,並把數據屬性,而不是代碼,您可以:

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

更妙的是,省略onclick和使用非侵入式JavaScript趕上點擊並添加行爲取決於class。然後,警告文本可以是.js文件中的靜態字符串。

0

\'得到由C#完全一樣'解釋。爲了在結果中包括反斜槓,你需要轉義反斜線本身:

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

你試過雙forwardslash? \」

或者你可以嘗試用它替換撇號的HTML代碼&apos;