John
John

Reputation: 1499

Trying to pass Array from Server Side to be read from Javascript in my MVC app

Any help much appreciated, not sure why this is not working, in my server side code i have:

foreach (var item in Model)
               {
                   if (item.SiteLocation == null || item.SiteLocation.SiteLocationId == 0)
                   { }
                   else
                   {

                       if ((item.SiteLocation.Latitude != 0) && (item.SiteLocation.Longitude != 0))
                           Page.ClientScript.RegisterArrayDeclaration("Sites", "'" + item.SiteId + "','" + item.SiteDescription + "','" + item.SiteLocation.Longitude + "','" + item.SiteLocation.Latitude + "'");
                   }

...........then i try to reference the array using the following code in Javascript :

    for (var i = 0; i < Sites.length; i++) {
        // Create and Element Object of type "option"
        alert(Sites[i]);
    }

..........but it says "Sites is undefined"

I've debugged server side and the "Page.ClientScript.RegisterArrayDeclaration" line runs a few times so no idea why object is not there when i use the Javascript, any ideas?

Upvotes: 1

Views: 986

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

  1. Page.ClientScript.RegisterArrayDeclaration?
  2. In an ASP.NET MVC application?
  3. Are you serious?

In an ASP.NET MVC application you use controller action which return ActionResults. So you could return JSON:

public ActionResult Foo()
{
    return Json(new[] { "elem1", "elem2" }, JsonRequestBehavior.AllowGet);
}

Then you could consume this controller action using AJAX for example.

Another possibility is to have this array as a property of your view model:

public ActionResult Foo()
{
    var model = new MyViewModel 
    {
        SomeArray = new[] { "elem1", "elem2" }
    };
    return View(model);
}

and then serialize this property in the view using JavaScriptSerializer:

<script type="text/javascript">
    var myArray = <%= new JavaScriptSerializer().Serialize(Model.SomeArray) %>;
    // TODO: now you can use the array as a native javascript object
</script>

Upvotes: 3

Related Questions