injection json data in the master page
I'd like to inject some javascript on every page; basically, it's a json string.
In my master page, I have this:
public partial class TheMasterPage : System.Web.UI.MasterPage
{
protected void Page_Init(object sender, EventArgs e)
{
if (Session["TheData"] == null)
{Session["TheData"] = GetData(DateTime.Today.Date;); }
}
}
This checks to see if the session contains the data I need for the json serialization.
What I'd like to do i开发者_运维知识库s have the data in the session to be included in the javascript of every page.
In the aspx of the page, I have:
<asp:ContentPlaceHolder id="head" runat="server">
<script type="text/javascript">
var TheJsonData =... ;
</script>
</asp:ContentPlaceHolder>
How do I inject the json data in there? If I do this, which gets executed first? The aspx injection or the Page_Init function?
I use the following code for the serialization:
TheDataList = (List<MyModel>)Session["TheData"];
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new MyModel() });
String result = serializer.Serialize(TheDatatList);
What I want to be able to do is $(document).ready(function () {ShowData(TheJsonData) }); with the variable TheJsonData already loaded when the document ready event fires.
Thanks.
Try like this:
<script type="text/javascript">
var TheJsonData = <%= new JavaScriptSerializer().Serialize(Session["TheData"]) %>;
</script>
And the end result should look something like this:
<script type="text/javascript">
var TheJsonData = [{ prop1: 'value1', prop2: 'value2' }, { prop1: 'value3', prop2: 'value4' }];
</script>
Page_Init
will run before the code in the view and would set the value in the session.
精彩评论