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 is 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:
And the end result should look something like this:
Page_Initwill run before the code in the view and would set the value in the session.