I have a create page that uses a JsonResult action instead of an ActionResult. In the ActionResult action, errors are displayed in the view next to the violation field. Right now, JsonResult returns only the string that appears in the warning window.
Is it possible to display ModelState errors in a view?
Controller
[HttpPost]
public JsonResult Create(Tload tload)
{
if (ModelState.IsValid)
{
...save changes
return Json(new { Success = 1, TransloadID = transload.TransloadID, ex = "" });
}
else
{
string totalError = "";
foreach (var obj in ModelState.Values)
{
foreach (var error in obj.Errors)
{
if (!string.IsNullOrEmpty(error.ErrorMessage))
{
totalError = totalError + error.ErrorMessage + Environment.NewLine;
}
}
}
return Json(new { Success = 0, ex = new Exception(totalError).Message.ToString()});
}
jquery / javascript code in view
function Save() {
...do stuff here
$.ajax({
url: '/Expedite/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
if (result.Success == "1") {
window.location.href = "/Expedite/index";
}
else {
alert(result.ex);
}
}
});
}
source
share