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"
});
}
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.