Knowing Modelstate in javascript dynamically

Asked

Viewed 112 times

0

I am developing an application in ASP.NET MVC 5 and I have a problem in putting a charging modal while the form is saved, because when there is something invalid in the form javascript does not respect, showing the charging modal, I would like to know how to take the dynamic Modelstate to release the modal only when it is true, thus avoiding to show the modal mistakenly.

I’m trying to use this way unsuccessfully:

$('#salvar').click(function () {
            var isValid = ${ViewData.ModelState.IsValid};
            if (!isValid) {
                waitingDialog.hide();
            } else {
                waitingDialog.show('Salvando Chamado...');
            }
        });
  • Which plug-ins are you using to validate the form on the front end? Unobtrusive Jquery?

  • @Vinicius, I am using the standard of ASP.NET MVC 5 Microsoftmvcvalidation.js

1 answer

0

First you have to understand that your code printing View (Html, css, javascript...) and rendering the code Razor (Which is a View Engine in the ASP.NET) is made at the moment when the request of your page is accepted by the server, thus causing nothing else encoded in Razor be interpreted again in that View.

When to make any request Ajax trying to pass a value rendered by Razor was already printed there at the beginning of the code rendering.

Follow the example:

Code html with the Razor:

@{
  ViewBag.StringTeste = "Renderizou!";
}

<script>
  function ImprimeValorRazor() {
      var stringExemple = '@ViewBag.StringTeste';
      alert(stringExemple);
  };
</script>

Rendered code:

<script>
  function ImprimeValorRazor() {
      var stringExemple = 'Renderizou!';
      alert(stringExemple);
  };
</script>

This control of ModelState is better controlled by your application and not by your View, because if the user changes the code through the browser will be able to cause exceptions directly in your application even skipping its validations.

Make it display a message to the user with the validations that did not pass on the return of your request or use the Data Notations directly within the entity for automatic validation.

Browser other questions tagged

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