Reputation: 367
I have a partial view (form) that I am displaying in a modal pop up. On submit it will create a new entry into the Database. This needs to be done via an ajax call. How do I pass all the form fields in the ajax call? I am using MVC4.
I tried $('form').serialize(), but this causes an error Invalid JSON primitive. What am I doing wrong?
var dataToSend = $('form').serialize();
$.ajax({
url: urlForSaving,
data: dataToSend,
cache: false,
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
success: function (data, status) {
},
error: function (xhr, ajaxOptions, thrownError) { alert('error') }
});
Controller
[HttpPost]
public JsonResult Add(SomeModel model)
{
if (ModelState.IsValid)
{
RedirectToAction("Index");
}
return Json(new {
Success = false,
Message = "Validation Errors"
});
}
Upvotes: 1
Views: 1085
Reputation: 352
From MVC3 and up I think it's an ideal situation to use Ajax.BeginForm in the partial view (as apposed to Http.BeginForm). The Ajax version automatically wires up everything for you including the post of the form via ajax.
Upvotes: 1
Reputation: 9448
You should add your field values to the object as below and then pass that object to a function which will be called on your required event.
var dataToSend = {
fieldname: $("FIELDCLASS OR ID").val();
};
function tocall(){
$.ajax({
url: urlForSaving,
data: JSON.stringify(obj:dataToSend),
cache: false,
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
success: function (data, status) {
},
error: function (xhr, ajaxOptions, thrownError) { alert('error') }
});
};
Upvotes: 1