Passing string parameter with alphabetic characters to a javascript function as argument fails
i tried to call a javascript function from codebehind(c#.net) with a parameter string parameter consisting of all alphabetic characters (eg: function1("fsdadfa");) and failed to get it worked. But when i changed the alphabetic characters with all numeric ones (eg:function1("12234");) it worked.
My code is as follows:
i used string.Format to call the function. My code is as follows:
string.Format("javascript:OpenNewsletter1({0},{1})",reader.GetInt("Id").ToString(),开发者_Go百科"dcsfs")
the problem arises with the 2nd parameter.
Any body know why it happened? if so please help me.
You need to encode it and use quotes:
string.Format("javascript:OpenNewsletter1({0}, '{1}')",
reader.GetInt("Id").ToString(),
HttpUtility.HtmlEncode("dcsfs"))
Notice the single quotes around the second parameter as well as encoding it because if the value contains special characters it might break your code.
The parameter is inserted in the format string as-is, so
string.Format("javascript:OpenNewsletter1({0},{1})",123,"dcsfs")
yields
javascript:OpenNewsletter1(123,dcsfs)
where javascript interprets dcsfs
as a variable name.
Try
string.Format("javascript:OpenNewsletter1({0},'{1}')",123,"dcsfs")
which will yield
javascript:OpenNewsletter1(123,'dcsfs')
that javascript will know to handle as a string literal.
I think you'll need to add quotes around the string (parameter {1}
) for javascript:
string.Format(
"javascript:OpenNewsletter1({0},\"{1}\")",
reader.GetInt("Id").ToString(),
"dcsfs")
精彩评论