AlexGH AlexGH - 5 months ago 19
C# Question

passing parameter in ajax gets null value

I'm calling an action controller using ajax but the parameter I'm passing with the

attribute is always null when the action controller receives it...
What could be happening in here?

JQuery function:

function PostOrder()
var id = $(".aslink").data("customerid");
var url = $("#btnAddOrderPost").data("url_add_order");
url: url,
data: JSON.stringify( { orderVM: $("#frmCreatePV").serialize()}),
datatype: "json",
contentType: "application/json",
success: function () {
alert("it was inserted");

Action controller:

// [ValidateAntiForgeryToken]
public ActionResult CreatePV(OrderVM orderVM)
if (ModelState.IsValid)
List<string> top = new List<string>();
decimal tempPrice = 0M;
for (int i = 0; i < orderVM.Toppings.Count; i++)
if (orderVM.Toppings[i].IsSelected == true)
tempPrice += orderVM.Toppings[i].Price;
Order order = new Order
Toppings = top,
TotalPrice = tempPrice
return RedirectToAction("Index");
return View(orderVM);

This is the OrderVM ViewModel I'm using a parameter of this type:

public class OrderVM
public virtual List<ToppingVM> Toppings { get; set; }
public decimal TotalPrice { get; set; }

And this is the form which is contained inside a Partial View:

@using (Html.BeginForm(null,null,FormMethod.Post, htmlAttributes: new { @id="frmCreatePV"}))
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
for (int i = 0; i < Model.Toppings.Count; i++)
<div class="col-xs-4">
@Html.HiddenFor(model => model.Toppings[i].SpecificTopping)
@Html.CheckBoxFor(model => model.Toppings[i].IsSelected, htmlAttributes: new { data_price = Model.Toppings[i].Price, @id = "chbkPrice" })
@Html.HiddenFor(model => model.Toppings[i].Price)
@Html.LabelFor(model => model.Toppings[i].IsSelected , Model.Toppings[i].SpecificTopping)
<p>Price: @Model.Toppings[i].Price</p>
<div class="form-group">
<div class="col-md-10">
<input type="button" value="Add order" id="btnAddOrderPost" class="btn btn-primary"
data-url_add_order="@Url.Action("CreatePV", "Orders")" />


Remove contentType will work for you.

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

When using contentType: 'application/json' you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.