Post JavaScript array with AJAX to ASP.Net MVC controller action

Post JavaScript array with AJAX to ASP.Net MVC Controller Action

Hello everyone, I am going to share the code sample for post a JavaScript array with AJAX to MVC controller action.

The Contents to post JavaScript array.

1.       You define your view models.
2.       Use your defined view models in controller action.
3.       You invoke to Action using AJAX POST.


Please follow the below steps to achieve it.

Step 1 : In the 1st step, you first define your view models.  For example you can see below.
        
        public class Orders
        {
            public int OrderID { get; set; }
            public string[] Products { get; set; }
        }

Step 2 : In the 2nd step, use your defined view models in controller action. for example you can see below

        [HttpPost]
        public ActionResult PostOrder(Orders model)
        {
            var yourOrderID = model.OrderID;
            var yourProducts = model.Products;

            //TODO: Your business Logic..

            return View();
        }

Step 3 : In the 3rd step, you finally call/invoke to Action using AJAX POST. for example you can see below

<script>
    var orderID ='PID1001'
    var products = ['P1', 'P2', 'P3'];
    var url = 'http://localhost:37745/Order/PostOrder';

    function postOrder(orderID, products, url) {
        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                OrderID: orderID,
                Products: products
            }),
            success: function (data) {
                alert('Success message.');
            },
            error: function (jqXHR, exception) {
                alert('Error message.');
            }
        });
    }
</script>

The detail example as given below

    public class OrderController : Controller
    {      
        [HttpPost]
        public ActionResult PostOrder(Orders model)
        {
            var yourOrderID = model.OrderID;
            var yourProducts = model.Products;

            //TODO: Your business Logic..

            return View();
        }
        public class Orders
        {
            public int OrderID { get; set; }
            public string[] Products { get; set; }
        }
    }




ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.