Saving Changes To The DB MVC
Solution 1:
I think you need contentType: 'application/json'
in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model
in your controller action.
Solution 2:
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8'
option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View()
is not applicable for AJAX response, use return PartialView()
instead and put html()
to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()
).
Post a Comment for "Saving Changes To The DB MVC"