passing paranter from asp.net to java script by JSON in html
I want o pass some JSON object in HTML response and eval it in client. I used fallowing code in server:
开发者_运维百科 TagBuilder tag = new TagBuilder("script");
tag.Attributes.Add("Id", id);
tag.Attributes.Add("type", "text/html");
tag.SetInnerText(new JavaScriptSerializer().Serialize(content));
return MvcHtmlString.Create(tag.ToString());
and I try to eval it in client :
var p = eval("(" + pEl.html() + ")");
but it didn't work because of encoding so I have to decode it by this:
var p = eval("(" + pEl.html().replace(/"/g,"'") + ")");
but it seem unpleasant , i try to use <%=%> in place of <%:%> in server side, but its remained same. any idea to solve problem? there is any better way to passing JSON along HTML response. Thanks
Try this:
TagBuilder tag = new TagBuilder("script");
tag.Attributes.Add("type", "text/javascript");
string json = new JavaScriptSerializer().Serialize(content);
tag.InnerHtml = "var p = " + json + ";";
return MvcHtmlString.Create(tag.ToString());
This declares a global javascript variable named p
which contains the json object you could use everywhere in your scripts and you don't have to worry about replacing quotes or calling eval
. You could name this variable using the id
parameter for example if you don't want it to be called p
.
精彩评论