Errors Model State Call Ajax

1

Good afternoon, I have a registration screen that I am making an ajax call to send the data, however when the user does not fill some field I need to show a field validation error message. In other sign-up screens on my system I used the @Html.ValidationMessageFor to report validation error however in that case it does not work since I am not doing the post inside the Html.BeginForm. Could anyone give me a hint of how I could display a validation error message in the default of Html.BeginForm without using Html.BeginForm?

 $.ajax({
            url: '/Teste/Save',
            data: JSON.stringify(salesmain),
            type: 'POST',
            contentType: 'application/json;',
            dataType: 'json',
            autoUpload: true,
            success: function (result) {
                if (result.success) {
                    location.reload();
                }
                else 
                {
                   
               
                    document.getElementById("btnsalvar").disabled = false; 
                }
            }
        });
    
asked by anonymous 08.03.2016 / 20:37

2 answers

1

My suggestion: Since you are posting using Ajax and have Model with properties and validations, you can continue doing server-side validation, but only reloading the form.

First step: Transform your form into a PartialView

I'll call it "_MyPartialView". Example:

//Não colocar funções javascript aqui, elas não funcionam em PartialViews, mova-as para a tela principal.
@model MeuModel;
<form>
    @Html.TextboxFor(x=>x.Codigo)
</form>

And on your main screen, render PartialView:

<div id="divPrincipal">
     @Html.Partial("_MinhaPartialView", Model)
</div>

Second step: Make your Controller return to PartialView in case of validation failure

[HttpPost]
public ActionResult Save(MeuModel model) {
    if(ModelState.IsValid) {
        return Json(new {success = true});
    }

    return PartialView("_MinhaPartialView", model);
}

Thus, on success, the form will return a json containing the indication that it was successful. In case of model validation failure, it will return a html containing the entire form, including the validation messages.

Third step: Rendering the return of your Ajax function

$.ajax({
        url: '/Teste/Save',
        data: JSON.stringify(salesmain),
        type: 'POST',
        contentType: 'application/json;',
        //dataType: 'json', <-- REMOVER ESTA LINHA, AGORA A FUNÇÃO RETORNA JSON E HTML
        autoUpload: true,
        success: function (result) {
            if (result.success) {
                location.reload();
            }
            else 
            {
                document.getElementById('#divPrincipal').innerHTML = result;
                //Alternativa caso você use jQuery: $("#divPrincipal").html(result);
            }
        }
    });

In this way divPrincipal will replace your current form, without validation, with a new form containing the validations and error messages without reloading the page. And if you return a JSon indicating success, it will reload the entire page.

    
08.03.2016 / 21:15
0

I found an article that explains how to do it. I tested it and it worked, follow the link:   link

    
08.03.2016 / 21:16