I have a problem and I don’t know what is the issue.
I am constructing a Json object and I want to post it back with $.ajax. The problem is I always get null in my Action.
here is Ajax Part :
$("input[type=button]#ajax-editor-save").click(function() {
var hotelPropertyAssignModel = new Object();
hotelPropertyAssignModel.Hotel_Id = 1;
hotelPropertyAssignModel.HotelProperties = new Array();
$("input.ajax-editor[data-edited=true]").each(function() {
var hotelPropertyValue = new Object();
hotelPropertyValue.HotelProperty_Id = $(this).attr("data-hotelPropertyId");
hotelPropertyValue.Language = $(this).attr("data-lang");
hotelPropertyValue.Value = $(this).attr("value");
hotelPropertyAssignModel.HotelProperties.push(hotelPropertyValue);
});
$.ajax({
url: '@Url.Action( "SetProperties" )',
type: 'POST',
dataType: 'json',
data: JSON.stringify(hotelPropertyAssignModel)
});
});
and here is Action:
[AcceptVerbs( HttpVerbs.Post )]
[HttpPost]
public void SetProperties ( string hotelPropertyAssignModel )
{
}
I changed the parameter to string to validate how json is coming. I get null when I replace it with correct model too!
anybody can help?
Make sure you set the proper contentType:
The
dataTypeparameter that you were using indicates the response type, not the request type. You don’t need it if your controller action properly sets the Content-Type response header which it normally does if you are returning for example a JsonResult.But from what I can see your controller action is declared as void which obviously is wrong. Controller actions must return action results. If you don’t care about the content, simply use an
EmptyResult:Also there’s another very serious problem with your controller action. It is taking a string argument instead of a view model!!! I don’t know how you were possibly expecting to bind a JSON request to some string.
So, immediately define a view model that will match the JSON structure you are willing to send:
and then have your controller action take this view model as parameter:
I also notice another problem with your code. You seem to have subscribed to the click event of some DOM element to trigger the AJAX request but you never cancel the default action by returning false from this event. So for example if this is a submit button or an anchor, it will simply redirect the browser away from the page leaving no time for your AJAX request to execute. So make sure you cancel this default action by returning false from your click handler: