how to deal with '&', '(', ')' in javascript
from my code behind i am passing this to client side script
C# code behind *note if i comment the below line than i dont get js error.*
if (btnDelete 开发者_StackOverflow社区!= null)
{
btnDelete.Attributes["onclick"] = String.Format("return DeleteRow('{0}', '{1}', '{2}', '{3}');", e.Row.ClientID, e.Row.RowIndex, DataBinder.Eval(e.Row.DataItem, "Id"), DataBinder.Eval(e.Row.DataItem, "Name"));
}
//javascript
function DeleteRow(rowId, rowIdx, Id, Name) {
var result = confirm('Are you sure you want to delete this record? \n\n Id: ' + Id + "\n Name: " + Name);
if (!result)
HighlightRow(rowId, rowIdx % 2 ? "#DEEEE9" : "#FFFFFF");
return result;
}
error message:
Message: Unterminated string constant
Line: 1280
Char: 180
Code: 0
URI: http://localhost:4964/admin/default.aspx
Message: Unterminated string constant
Line: 1341
Char: 178
Code: 0
URI: http://localhost:4964/default.aspx
Message: Expected ')'
Line: 1401
Char: 152
Code: 0
URI: http://localhost:4964/default.aspx
It's hard to tell from your question, but it sounds like the values that are being returned are including the single quote character (apostrophe) which would end your string in the resulting javascript.
What is the code that is being generated for the lines that are throwing the error?
When similar things have happened to me it resulted in something like:
return DeleteRow('1', '2', 'abscde', 'Mc'Adams');
Which would cause an error because of the value Mc'Adams. If that is the case then you'll have to send your data through a method that escapes values that would otherwise corrupt your javascript.
You've used mixed single and double quotes. Change the line here;
var result = confirm('Are you sure you want to delete this record? \n\n Id: ' + Id + '\n Name: ' + Name)
here is how i abel to fix it:
btnDelete.Attributes["onclick"] = String.Format("return DeleteRow('{0}', '{1}', '{2}', '{3}');", e.Row.ClientID, e.Row.RowIndex, DataBinder.Eval(e.Row.DataItem, "Id"), DataBinder.Eval(e.Row.DataItem, "Name").ToString().Trim().Replace("'", "\\'")));
精彩评论