I think the best in this case would be to create a partialView where you would work the errors and then use the screen and return to Partialview;
Example:
1 - Partial error: "_Validationsummary.cshtml"
@if (!Html.ViewData.ModelState.IsValid)
{
<div class="alert alert-danger" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<p class="text-center"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Alerta!</p>
<div class="validation-summary-errors">
@foreach (var modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
//aqui você tem seus erros. Trabalhe neles no padrão que precisar.
}
}
</div>
</div>
}
Controller:
using System.IO;
using System.Linq;
using System.Web.Mvc;
public ActionResult SaveInternalAuditRecord(InternalAuditRecord criticalAnalysisRecord, string idResponsibles, string idAuditors)
{
if (!ModelState.IsValid)
{
ModelState.OrderByKeys(criticalAnalysisRecord.GetValidationOrder());
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new
{
RenderPartialToString("~/Views/Layout/_ValidationSummary.cshtml", null, ControllerContext, string.Empty)
}, JsonRequestBehavior.AllowGet);;
}
}
private string RenderPartialToString(string viewPath, object model, ControllerContext controllerContext, string partialFieldName)
{
var viewData = new ViewDataDictionary();
var tempData = new TempDataDictionary();
viewData.Model = model;
if (!string.IsNullOrWhiteSpace(partialFieldName))
{
viewData.TemplateInfo.HtmlFieldPrefix = partialFieldName;
}
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewPath);
var viewContext = new ViewContext(controllerContext, viewResult.View, viewData, tempData, sw);
if (controllerContext != null)
foreach (var item in controllerContext.Controller.ViewData.ModelState.Where(item => item.Value.Errors.Any()))
viewContext.ViewData.ModelState.Add(item);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
then you just replace it with your ajax, as you are already doing in your code;
Partialview() makes the knockoutjs to work was using so
– Bruno H.
I edited my reply @Brunoh. Now it will mount the html in your controller and will return as string. Then only you put in your html via ajax
– Ayrton Giffoni
the ideal would be for you to put this Renderpartialtostring method in a utility class and leave the static method.
– Ayrton Giffoni
He gave some error, but now I’m bringing the message only that is not drawn right comes a " " seems edited.
– Bruno H.
He adds an <li></li> plus
– Bruno H.
Oh yes, I get it. That’s the @Html.Validationsummary() that does it. You can look at a way to manually bring up your mistakes. I’ll search here and edit my answer to help you.
– Ayrton Giffoni
I’ll update the image
– Bruno H.
Let’s go continue this discussion in chat.
– Bruno H.