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

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

Post JavaScript array with AJAX to ASP.Net MVC Controller Action Post JavaScript array with AJAX to ASP.Net MVC Controller Action Reviewed by Anil Singh on 10:00 PM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^