Problems with IF in javascript

Asked

Viewed 266 times

7

I’m a beginner in Asp.Net MVC, and I’m developing an application that manages Courses and in my screen of enrollment I’m trying to do a validation javascript what case the pupil is already enrolled in a course and he tries to enroll again in that same course, should appear one popup javascript with the message You are already enrolled in this Course. The other validation is when the number of vacancies come to zero, the status of the course must change to Closed instead of being like Course Available. I tried to do so:

View Registration

@model IEnumerable<MeuProjeto.Models.Curso>

<style>
    #Status {
        display: block;
        text-align: center;
    }

    .encerrado {
        background-color: green;
        font-family: 'Times New Roman';
        color: white;
    }

    .disponivel {
        background-color: orange;
        font-family: 'Times New Roman';
        color: white;
    }

</style>

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

<table class="table table-hover">
    <tr>
        <th>
            Curso
        </th>
        <th>
            Sigla
        </th>
        <th>
            Ementa
        </th>
        <th>
            Inicio
        </th>
        <th>
            Fim
        </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.Turno)
            </td>
            <td>
                <input type="text" name="Status" id="Status" value="@Html.DisplayFor(modelItem => item.Status)" readonly class="Status" />
            </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>
        function Alerta() {
            var val = document.getElementsByClassName("inscricao").value;

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

            if (st != "Curso Disponível") {
                st = "encerrado";
            }
        }
    </script>

    <script>
        $(document).ready(function() {
            $('.Status').each(function() {
                if ($(this).val() == "Curso Disponível") {
                    $(this).addClass("disponivel");
                }
                if ($(this).val() == "Encerrado") {
                    $(this).addClass("encerrado");
                }
            });
        });
    </script>
}
  • 1

    The best thing would be to take advantage of Ajax that has already called the subscription method and return a JSON with the status. Depending on the returned message, you return a different message.

  • Gypsy is right. You make an AJAX call, your alert should be on the return of this call, not in the event click the registration link. In the status function, when you do st="terminated", you are modifying only the variable st, not the element "inscription".

  • But it is not clear where/what is going wrong in your code. Try to explain better the result you are getting and why it is not good.

  • Well, in my IF’s of alert is always falling for this message alert("Você já está cadastrado nesse Curso!"), namely in the else, regardless of null or not. @Gypsy you could give me some example of JSON, I still don’t know how to use it.

1 answer

1

Beginner. I agree with Gypsy, the ideal is to make an ajax request to the server and check whether the course is available or not.

Before going into detail about how to do this, it is worth explaining the reason for the problem you are facing.

The method document.getElementsByClassName("inscricao") will return an array of html elements, not a specific element. Whenever you use this method, even if there is only one element in the DOM with this class, always enter the index of the array. Ex. document.getElementsByClassName("inscricao")[0].value

Since you did not enter the array index, the variable value val will always be undefined.

A way to get the value of the element that received the click would be like this:

$(".inscricao").click(function() {
    var val = $(this).val();
    if (!val)
    {
        alert("Cadastro realizado com Sucesso!");
    } 
    else 
    {
        alert("Você já está cadastrado nesse Curso!");
    }

});

To make the validation as suggested by Gypsy you could do something like this:

Javascript

<script>
    $(document).ready(function() {
        $(".inscricao").click(function() {
            $.ajax({
                type: "POST",
                url: "/Inscricao",
                data: { inscricaoId: $(this).data("inscricaoid") },
                success: function(retorno) {
                    alert(retorno);
                }
            });
        });
    });
</script>

C# (Controller)

public class InscricaoController : Controller
{

    public ActionResult Index(int inscricaoId)
    {
        string mensagem = "";

        if (ValidarInscricao(inscricaoId))
        {
            MetodoParaFazerAInscricao();
            mensagem = "Cadastro realizado com Sucesso!"
        }
        else
        {
            mensagem = "Você já está cadastrado nesse Curso!";
        }

        return Json(mensagem);
    }

}

Browser other questions tagged

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