Errors Model State Called Ajax

Asked

Viewed 337 times

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 screens of registration of my system I used the @Html.Validationmessagefor to inform validation error however in this case it does not work because I am not doing the post inside Html.BeginForm. Someone could give me a hint as to how I could show a validation error message in the Html.Beginform default 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; 
                }
            }
        });

  • In this case you own one Model containing the validation properties (as is done in the Html.BeginForm() common) or is a "dry form"?

  • @Thiagoferreira Has a Model with the validation properties in the column that uses Html.Beginform().

2 answers

1

My suggestion: Since you are posting using Ajax and own a Model with properties and validations, you can continue to validate on the server side, but reload only the form.

First Step: Turn your form into a PartialView

I will call it "_Minhapartialview". 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 the 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);
}

So, if successful, the form will return a json indicating that it has been successful. In case of model validation failure, it will return a html containing the entire form, including validation messages.

Third step: Render 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);
            }
        }
    });

Thus the 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, you will reload the full page.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.