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.
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; }
}
}