views:

33

answers:

1

Hi

I have a ASP.NET MVC 1.0 app.

I have a listbox on the page and I want to pass an array to the webpage so that javascript can use the array to do some processing depending on the item picked in the listbox.

So I thought the best way is to pass JSON data to the webpage on load.

So what is the best practice on how to do this?

Can you please give me a brief step by step process.

How do pass the array as JSON and how do I access it by index?

Appreciate someone getting me started on this.

Malcolm

+1  A: 

Controller action:

public ActionResult Values(string someParameter) 
{
    return Json(new[]
    {
        new { Id = 1, Value = "value 1" },
        new { Id = 2, Value = "value 2" },
        new { Id = 3, Value = "value 3" },
    });
}

Javascript:

$.getJSON('<%= Url.Action("values") %>', { someParameter: 'some value' }, function(result) {
    $(result).each(function(index, item) {
        // TODO: Use item.Id and item.Value here
    });

    // or simply access the result variable by index ...
});
Darin Dimitrov