Monday, February 28, 2011

Iterating the list on jQuery from the list returned by ASP.NET MVC function

Given this:

<script type="text/javascript">
    function testList() {
        $.ajax(
        {
            url: '/Music/List/',
            type: 'POST',
            dataType: 'json',
            success: function (result) {
                $.each(result.Songs, function () {
                    alert(this.Title + ', ' + this.Album + ', ' + this.YearReleased );
                });
            }
        });
    }
</script>

And this:

<input type="submit" value="Test" onclick="testList(); return false;" />

And this model:

namespace SampleJquery.Models
{
    public class Song
    {
        public string Title { get; set; }
        public string Album { get; set; }        
        public int YearReleased { get; set; } 
    }
}

This is how your ControllerHere/MethodHere shall look like:

namespace SampleJquery.Controllers
{
    public class MusicController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public JsonResult List()
        {
            return Json(
                new 
                { 
                    Songs = 
                        new Song[]
                        {
                            new Song { Title = "Taxman", Album = "Revolver", YearReleased = 1966 },
                            new Song { Title = "Girl", Album = "Rubber Soul", YearReleased = 1965 },
                            new Song { Title = "Come together", Album = "Abbey Road", YearReleased = 1969 }
                        }
                });
        }

    }
}

Notice that in jQuery's AJAX call, we don't invoke the full controller name (i.e. MusicController), we just need to invoke the function using the controller's public url slash method:

url: "/Music/List/",



If plain javascript is desired for iterating the list, you can use:

<script type="text/javascript">
    function testList() {        
        $.ajax(
        {
            url: '/Music/List/',
            type: 'POST',
            dataType: 'json',
            success: function (result) {                
                for (var i in result.Songs) {
                    var song = result.Songs[i];
                    alert(song.Title + ', ' + song.Album + ', ' + song.YearReleased);
                }
            }
        });
    }
</script>

But please do bear in mind that you will bear the wrath of jQuery peeps by doing so :D lol

No comments:

Post a Comment