1

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?

1
  • Thanks Adrian, i've went over my previous posts and flagged as answered,cheers, J Commented Dec 2, 2010 at 9:28

1 Answer 1

3
  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>
Sign up to request clarification or add additional context in comments.

2 Comments

I 100% second this answer. @John: Remember that in MVC, the "code-behind" has no connection to the View other than the model that it passes in to it.. As a matter of fact, there is no such thing as code-behind in MVC, unless you actually add a webforms-page to your app...
I could only add comments to this but needed to supply more info. Thanks for the help Darin, are you able to view this link if you have a spare minute, mayn thanks, j stackoverflow.com/questions/4345281/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.