views:

14

answers:

1

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

+1  A: 

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.

Darin Dimitrov
No , its not work, its render " as " yet and so its not accepted as JavaScript by IE.
mehran
Correct, I'm sorry, please see my update, use `InnerHtml` as `SetInnerText`.
Darin Dimitrov