Fabio Santos Fabio Santos - 3 months ago 12
Ajax Question

ASP net 4 send object from ajax nullexceptionReference

I try to send a object from the form to a HttpPost method(who recives a object parameter) but i get always a NullExceptionReferece but if I pass as string I don't get the error.
My controller:

[HttpPost]
//public ActionResult CheckVat(string vatnumber) {
public ActionResult CheckVat(VatSearch vatnumber)
{
return Json(vatnumber);
}


my ajax function:

<h3>Insert VAT number to check:</h3>
@model LatourretrVat.Models.VatSearch

<form id="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
@Html.TextBoxFor(m => m.VatNumber,new { @class = "form-control", @id="VatNumber"})
@Html.ValidationMessageFor(model => model.VatNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Check VAT" />
</div>
</div>
</div>
</form>
<script >
$(document).ready(function () {
$('#form').submit(function () {
var VatSearch = new Object();
VatSearch.VatNumber = $("#VatNumber").val();
$.ajax({
url: '@Url.Action("CheckVat", "Home")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({
// VatNumber: $('#VatNumber').val(),
//}),
data: JSON.stringify(VatSearch),
success: function (result) {
alert("success");
},
error: function (result) {
console.log(result);
alert("error");
}
});
return false;
});
});
</script>

Answer

Your HttpPost action method parameter's name should not be same as one of the properties of the parameter type.

Currently your user vatnumber as the parameter type and i assume your view model also has a property called VatNumber.

This should work.

[HttpPost]
public ActionResult CheckVat(VatSearch data)
{
   return Json(data);
}

Also, there is no need to specify the dataType as "json" as you are explicitly sending json response from the server.