Errors
public List<string> GetModelStateErrors(ModelStateDictionary ModelState)
{
List<string> errorMessages = new List<string>();
var validationErrors = ModelState.Values.Select(x => x.Errors);
validationErrors.ToList().ForEach(ve => {
var errorStrings = ve.Select(x => x.ErrorMessage);
errorStrings.ToList().ForEach(em => {
errorMessages.Add(em);
});
});
return errorMessages;
}
if (!ModelState.IsValid)
{
return Json(new { success = false, errors = GetModelStateErrors(ModelState) }, JsonRequestBehavior.AllowGet);
}
function displayValidationErrors(errors)
{
var $ul = $('div.validation-summary-valid.text-danger > ul');
$ul.empty();
$.each(errors, function (idx, errorMessage) {
$ul.append('<li>' + errorMessage + '</li>');
});
}
That's how we handle it via ajax:
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
var isSuccessful = (data['success']);
if (isSuccessful) {
$('#partial-container-steps').html(data['view']);
initializePage();
}
else {
var errors = data['errors'];
displayValidationErrors(errors);
}
}
});
Render partial views via ajax in the following way:
var view = this.RenderRazorViewToString(partialUrl, viewModel);
return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Simple line to return errors
|
You can do it this way:
(Edit: Considering that you're waiting for a response
json with dataType: 'json' )
.NET
JS:
|