Sirisha Ancha Team : Web Development Tags : Web Development jQuery MVC

Ajax with MVC - Passing HTML data as a list of objects

Sirisha Ancha Team : Web Development Tags : Web Development jQuery MVC

Consider the following scenario:

We need to pass list of Products and a statusId to the controller action UpdateProducts.

Product:

        public class Product
        {            
            public int Id { get; set; }
<span class="redactor-invisible-space">            public int StatusId { get; set; }
...</span>
            public string Name { get; set; }
        }

Controller:

        public async Task<ActionResult> UpdateProducts(List<Product> products, int statusId)
        {
            //Your logic here using Products and statusId 
            return Json(new { @success = true });
        }

To achieve this we need to build the Products object and then stringify it into one object for the data to be passed as expected.

Script:

        var products = $('#productTable input[type="text"]').map(function ()
        {
            var obj = new Object();
            obj.Id = $(this).data("id");
            obj.Name = $(this).val();
            ...
            obj.Status = 1;
            return JSON.stringify(obj); //stringify individual Product 
        }).get();
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: '@Url.Action("UpdateProducts")',
                type: 'post',
                data: JSON.stringify({ products: products, statusId: 1}) //stringify the whole data again
            })
            .done(function (result)
            {
                 //result here
            });

For it to work, JSON.stringify needs to be applied to each object, and again to the whole output as shown in the above example.

This feature lets you pass complex data to a MVC controller.