I frequently write client side code in the code-behind section 开发者_如何转开发of my asp.net applications. I think its about time to get a refresher on how to write client side code on server side page.
I need to refresh mysel fwith the "double quotes" and "single quotes". Not sure what that is called, but can anyone point me to the correct resource where I can learn about the quotes and double quotes.
Writing javascript code, intended to be run on the client, on the server is to put it simply: bad, wrong, to be avoided.
You should prefer to write your javascript functions in separate js files and only invoke them from the server. The benefit of this is that you will no longer have to worry about single, double and triple quotes, your js will be cached, minified, gzipped, served from a CDN, optimized, ... The end result of mixing server side languages such as C#/VB.NET with javascript is just ugly and difficult to maintain code.
Now to the point. When you need to call some javascript function from the server and you need to pass it some arguments in order to not worry about quotes and stuff, I would recommend you to JSON serialize your server side object and pass it to the client function.
Let's take an example. Suppose that you have written a function which requires some arguments:
function foo(myModel) {
alert(myModel.Prop1 + ' | ' + myModel.Prop2);
}
and now you want to invoke this function from the server, here's how to proceed:
var model = new
{
Prop1 = @"some value that can contain ', \, "", anything you like to throw it in, etc..",
Prop2 = "some other value"
};
var json = new JavaScriptSerializer().Serialize(model);
var script = string.Format("foo({0});", json);
ClientScript.RegisterStartupScript(GetType(), "foo", script, true);
Now you no longer need to worry about any quotes and escaping. No matter what value you throw in those properties, they will be correctly serialized when invoking the javascript function.
精彩评论