简体   繁体   中英

Parse 2D array from ASP.NET C# code behind to Javascript

I've written a function (addCalendarEvents) which takes in an array (events) and parses into a custom calendar. Everything works perfectly fine when its fired through the document.ready function, events are registering and etc.

Javascript

$(document).ready(function () {
    loadCalendar(null);
    addCalendarEvents([{ title: 'All Day Event', start: '2016-01-01' }, { title: 'Long Events', start: '2016-01-07', end: '2016-01-10' }]);     
});

function addCalendarEvents(events) {
    $('#calendar').fullCalendar('addEventSource', events)
}

However, I also need them to be fired through the code behind to add events dynamically. I've tried using ScriptManager's RegisterStartupScript, but it's not working. Is there a proper way for me to do so?

C# Code Behind

protected void Page_Load(object sender, EventArgs e) 
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), "addEvents", "addCalendarEvents([{ title: 'Other Event', start: '2016-01-01' }, { title: 'Other Long Events', start: '2016-01-07', end: '2016-01-10' }]);", true);
}

try to convert the data into json while adding the script. Add your assemblies

using this Assembly
using System.Web.Script.Serialization;

Then Deserialize your object

var json = new JavaScriptSerializer().Serialize(obj);

then call registerStartupScript

ScriptManager.RegisterStartupScript(this, this.GetType(), "addEvents", json, true);

and at client side do this to convert it into json

var obj = JSON.parse(string);

It might be simpler to use a <asp:Literal id="StartupScript" runat=server /> control containing the $(document).ready() function to inject your page load callouts.

You could write the statements to the literal control within your Page_Load event and they should get executed by the client when the page is ready.

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <asp:Literal ID="CodeInject" runat="server"/> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html> 

And the code behind is:

 protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder SB = new StringBuilder();
        SB.Append("<script>");
        SB.Append("$(document).ready(function () {");

        // statements here
        SB.Append("alert('test');");


        SB.Append("});</script>");
        CodeInject.Text = SB.ToString();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM