Validation via Javascript

Asked

Viewed 511 times

2

In my application that manages Courses, I need a validation via javascript. I have a screen where the pupil makes his registration in a certain course, what I wanted is that when he click the button enrollment the message appeared Registration made with success, and the other is when he tries to sign up in the same course, in this house should appear the message You are already enrolled in this course. I tried to make it the way down in function Alerta but my message only falls on else. Can someone help me?

My View

@model IEnumerable<MeuProjeto.Models.Curso>

<h2>Catálogo de Cursos</h2>

<span class="pull-right">
    @using (Html.BeginForm("Inscricao", "Curso", FormMethod.Get))
    {
        <p>
            Pesquisar Curso: @Html.TextBox("pesquisar")
            <input type="submit" value="Pesquisar" class="btn btn-primary" />
        </p>
    }
</span>

<table class="table table-hover">
    <tr>
        <th>
            Curso
        </th>
        <th>
            Sigla
        </th>
        <th>
            Ementa
        </th>
        <th>
            Inicio
        </th>
        <th>
            Fim
        </th>
        <th>
            Carga Horária
        </th>
        <th>
            Turno
        </th>
        <th>
            Status
        </th>
        <th>
            Quantidade de Vagas
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
           <td>
                @Html.DisplayFor(modelItem => item.Nome_Curso)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Sigla)
            </td>
            <td>
                <a href="~/Curso/[email protected]">Ementa</a>
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Dt_Inicio)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Dt_Fim)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Carga_Horaria)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Turno)
            </td>

            <td>
                @Html.DisplayFor(modelItem => item.Qtd_Vagas)
            </td>
            <td>

                <div class="btn-group">
                    <div class="col-md-offset-2 col-md-10">
                        @using (Html.BeginForm("Inscricao", "Curso", FormMethod.Post))
                        {
                            if (item.Qtd_Vagas > 0)
                             {
                                 <a class="inscricao btn btn-success" onclick="$(this).parents('form').submit(), Alerta()">Inscrição</a>
                                 <input type="hidden" value="@item.Id" name="inscricaoId" />
                             }
                            else
                            {
                                 <input type="submit" value="Não há vagas" name="detalhes" class="inscricao btn btn-default" disabled="disabled"/>
                            }
                        }
                    </div>
                </div>
            </td>
        </tr>

    }

</table>
<div class="form-group">

    <a href="@Url.Action("HomeAluno", "Home")"><input type="button" value="Voltar" class="btn btn-danger" /></a>

</div>
<br />


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        $(document).ready(function() {
            $(".inscricao").click(function() {
                $.ajax({
                    type: "POST",
                    url: "Inscricao/",
                    data: { inscricaoId: $(this).data("inscricaoid") },
                    success: function() {
                        window.location.reload();
                    }
                });
            });
        });
    </script>
    <script>
      <--! TENTEI FAZER ASSIM, MAS SÓ ME APARECE A MENSAGEM DO ELSE -->
        function Alerta() {

            if (document.getElementsByClassName("inscricao").value == null) {
                alert("Cadastro realizado com Sucesso!");
            } else {
                alert("Você já está inscrito nesse Curso!");
            }
        }
    </script>

}

My Action Registration

    [HttpPost]
    public ActionResult Inscricao(int inscricaoId, string pesquisar)
    {
        using (var scope = new TransactionScope())
        {
            //Aqui pega o usuario logado
            Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
            if (aluno == null)
                return View("MeusCursos");

            //Aqui pega o curso selecionado
            var curso = db.Cursos.FirstOrDefault(c => c.Id == inscricaoId);
            if (curso == null)
                return View("MeusCursos");

            //Aqui verifica se o aluno já está inscrito em algum curso
            var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Curso.Id == inscricaoId && ac.Aluno.Usuario == User.Identity.Name);
            if (alunoCurso != null)
            {
                return RedirectToAction("Inscricao", "Curso");
            }

            //Aqui faz a associação do Aluno e Curso
            alunoCurso = new AlunoCurso
            {
                Aluno = aluno,
                Curso = curso
            };

            db.AlunoCursos.Add(alunoCurso);
            db.SaveChanges();

            //Aqui decrementa a quantidade de vagas dos Cursos
            curso.Qtd_Vagas--;
            db.Entry(curso).State = EntityState.Modified;
            db.SaveChanges();

            scope.Complete();
        }

        var cursos = from c in db.Cursos select c;

        if (!String.IsNullOrEmpty(pesquisar))
        {
            cursos = cursos.Where(c => c.Nome_Curso.Contains(pesquisar));
        }
        cursos = cursos.OrderBy(a => a.Nome_Curso);

        return View(cursos.ToList());
    }

2 answers

1

I saw the doubt in the comments above and decided to reinforce what our friend @Fernando Medeiros said in his own code!

in your script tag in your Success you will make the following change:

<script>
    $(document).ready(function() {
        $(".inscricao").click(function() {
            $.ajax({
                type: "POST",
                url: "Inscricao/",
                data: { inscricaoId: $(this).data("inscricaoid") },
                success: function(data) {
                     /*se o seu retorno dentro do JSON for true quer dizer que está tudo OK! então será efetuado o redirect! Certo ?*/
                     if(data == true) {
                         alert("usuario cadastrado com sucesso :D");
                         window.location.reload();
                     }
                     /*Já se o mesmo vier como falso ele não entrá no if será exibido o alerta para seu usuário!*/
                     alert("você já está inscrito nesse curso")
                }
            });
        });
    });
</script>

Now let’s go to change your action ..

[HttpPost]
public ActionResult Inscricao(int inscricaoId, string pesquisar)
{
    using (var scope = new TransactionScope())
    {
        //Aqui pega o usuario logado
        Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
        if (aluno == null)
            return View("MeusCursos");

        //Aqui pega o curso selecionado
        var curso = db.Cursos.FirstOrDefault(c => c.Id == inscricaoId);
        if (curso == null)
            return View("MeusCursos");

        //Aqui verifica se o aluno já está inscrito em algum curso
        var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Curso.Id == inscricaoId && ac.Aluno.Usuario == User.Identity.Name);
        if (alunoCurso != null)
        {
            /*Aqui vamos retornar o JSON para seu javascript mostrar o alert fora do if vamos retornar um false para o mesmo*/
            return new JsonResult() { Data = false, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        //Aqui faz a associação do Aluno e Curso
        alunoCurso = new AlunoCurso
        {
            Aluno = aluno,
            Curso = curso
        };

        db.AlunoCursos.Add(alunoCurso);
        db.SaveChanges();

        //Aqui decrementa a quantidade de vagas dos Cursos
        curso.Qtd_Vagas--;
        db.Entry(curso).State = EntityState.Modified;
        db.SaveChanges();

        scope.Complete();
    }

    /*E para finalizar ao invés de retonar uma nova view para seu ajax vocÊ vai retornar um json confirmando que o mesmo foi salvo com sucesso, sua aplicação mostrará o alert e depois recarregara sua pagina*/
    /*Vale também lembrar que no data onde retorno false pode ser retornado varias outras informações como um objeto ou string .. que pode ser tratada pelo seu javascript :D*/
    return new JsonResult() { Data = true, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

}

NOTE: The implementation is the same as our friend @Fernando Medeiros

I hope I helped :D

1

It is possible to use the Success function to solve both problems, in the Action "Registration" you must keep the current code, adding only a validation to check if the user is already registered for that course, if he is not registeredhow it was doing before and return a JSON object at the end warning that the registration was performed.

In the Action part what will change is the return, as it is a registration via AJAX before you did not return anything, but it is possible to return a JSON object, defining an attribute of your choice and the value of it, such object can be consulted in the AJAX Function Success, carrying out the necessary logic based on it.

To solve your problem we will return an attribute called 'Success', if the value is 'true' the user was registered, if it is 'false' is because it is already registered in the course, follow example:

Return Json in Action

public ActionResult Inscricao(/*seus parametros*/ ){
/*coloque aqui o código para enviar a view de inscrição com seus parametros*/
    return View();
}



//essa Action deve ser usada somente por Ajax para conferir o cadastro
[Http.Post]
public ActionResult Inscreve(int InscricaoID){
    if(/* crie um código para validar se já está no curso*/){
          return Json( new {success = "false"});
    }
    else{
       /* coloque aqui o seu código atual de cadastro */
         return Json( new {success = "true"});
    }    
}

Javascritp code of ajax

 <script>
        $(document).ready(function() {
            $(".inscricao").click(function() {
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("Inscreve")",
                    data: { inscricaoId: $(this).data("inscricaoid") },
                    success: function(objetoJson) {
                        if(objetoJson.success == true)
                           alert('O cadastro foi realizado com sucesso!');
                        else
                           alert('Você já está inscrito nesse Curso');
                    }
                });
            });
        });
    </script>

So working with json objects in the Action response and analyzing these responses in the AJAX Success function you can solve this problem of yours.

  • These returns come in Popup @Fernandomedeiros?

  • the return will come encapsulated in a Json object, this object can be manipulated if placed as parameter of Function Success, in which case what creates the popup is the function "Alert()" of javascript

  • That Return Json I put in mine Action?

  • I wouldn’t have a way to do that with the javascript not @Fernandomedeiros, with Json had problems.

  • Check the edition I made in the reply, now should work with JSON

  • I put my Action on the question @Fernandomedeiros.

  • Friend, because it is an Action used by AJAX, it does not have because you return a View, the View represents HTML to be sent for representation of the browser, in your case for what seems is only necessary the signaling of whether the user was registered or not, then exchange the View returns for Json’s return given what I used in my example

  • In case my answer has been useful please evaluate it, thank you

  • I just need a simple Lert javascript

  • This is what is implemented in my example, do what I said, return JSON instead of View, if Voce uses this action for other purposes, create a new Action to do this part of user registration, in this case it would be necessary to change the path of the URL in AJAX

  • Precisely, I would have to make more changes to my action and have to create another one. The message that Json is returning to me is this {"sucess":"false"} redirecting me to a page only with this message, and not a Popup.

  • Create a unique Action for user registration, you are misusing the MVC design, create an Action for each function, is returning this JSON because Voce uses the same Action to return the View form

  • Check my change in response.

  • In this mine action i do not do any user registration. I only do one thing that is: In this my action has a list of courses and a button enrollment but it is course registration, the pupil already registered in the system just click on the button and should appear messages: Registration made with success. and if he tries to enroll in the same course again You are already enrolled in this course.

Show 9 more comments

Browser other questions tagged

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