How to pass values to an external Javascript script from ASP.NET

  asp.net, asp.net-mvc, c#, html, javascript

I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag… Here is what is in the controller:

    public ActionResult KPI()
    {
        if (Session["OrganizationID"] == null)
        {
            return RedirectToAction("Unauthorized", "Home");
        }

        else
        {
            int orgId;
            int.TryParse(Session["OrganizationID"].ToString(), out orgId);
            var user = db.Users.Find(User.Identity.GetUserId());
            var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
            var reports = db.Reports.ToList();

            try
            {
                var org_reports = (from r in reports
                                   where r.OrganizationID == organization.OrganizationID
                                   select r).ToList();                    
                
                var kpi = new KPI(org_reports);
                var jsonKPI = JsonConvert.SerializeObject(kpi);
                ViewBag.orgData = jsonKPI;
            }
            catch (ArgumentNullException e)
            {
                return RedirectToAction("Unauthorized", "Home");
            }
        }
        return View();
    }

From the View I’ve tried using hidden values, and also just passing them in as parameters when calling the script:

<input  type="hidden" id="orgData" [email protected]>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
    orgData = @ViewBag.orgData;
</script>

I then want to read this value in my JS script and parse it into JSON from the string:

function myFunction(){
   var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
   var test2 = JSON.parse(orgData); // Doesn't work
}

It doesn’t appear that any of these methods are working. What is my mistake here?

Source: Ask Javascript Questions

LEAVE A COMMENT