Reputation: 397
I am using MVC and have a form in my view as follows
@using(Html.BeginForm(null, null, FormMethod.Post)) {
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.SysCreated)
@Html.HiddenFor(m => m.SysDeleted)
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
<input typeof="button" value="Create New" onclick="newSchool(this)" class="btn btn-sm btn-primary btn-block btn-signin" style = "margin-bottom:20px" / >
}
I am trying to post this using a javascript function so that I avoid the page refreshing. I have the following function
function newSchool(btnClicked) {
var $form = $(btnClicked).parents('form');
var data = $form.serialize();
console.log(JSON.stringify(data));
$.ajax({
url: '@Url.Action("AddSchool", "SetupSchools")',
type: 'POST',
contentType: "json",
data: {
newSchool: JSON.stringify(data)
},
success: function() {
DevExpress.ui.notify('School Added', 'success', 1500);
},
failure: function(xhr, textStatus, errorThrown) {
DevExpress.ui.notify('Error - ' + XMLHttpRequest.responseText, 'error', 1500);
},
});
}
I can see in the console that the data is there and looks correct, however the data in my controller is always null. My controller looks like the following
public void AddSchool(Models.School school)
{
}
How can I send the data correctly? Alternatively, is there a better way to post the data without refreshing the form.
Upvotes: 1
Views: 780
Reputation: 693
As some of the comments suggested, you need to remove the contentType: json
and use data: $("form").serialize()
, and my personal recommendation is to use cache: false
to always send the data to the controller, if I not mistaken, IE used to cache the ajax request if it looks the same.
Here is a "fiddle" you can see it's working with you current code:
https://dotnetfiddle.net/IGaQnt
And your code should be like that:
function newSchool(btnClicked) {
var $form = $(btnClicked).parents('form');
var data = $form.serialize();
console.log(JSON.stringify(data));
$.ajax({
url: '@Url.Action("AddSchool", "Home")',
type: 'POST',
cache: false,
data: data,
success: function(result) {
alert(result); //I return the name the user submited, you can do whatever you want here.
},
failure: function(xhr, textStatus, errorThrown) {
DevExpress.ui.notify('Error - ' + XMLHttpRequest.responseText, 'error', 1500);
},
});
}
I decided to use in the fiddle a JsonResult
insted of a void
, I don't know you complete code so change it as you need.
Upvotes: 1
Reputation: 17
I'm assuming that school has as properties the elements on your form, so if that's correct what you have to do is to use $form.serializeArray() to get the data in json format and send that variable on your asynchronous request. I think the error is because you create an object newschool and assign all the data to that object, but what you are expecting in the controller is the data not that object.
Upvotes: 0