Problem with a Count in Asp.Net MVC

Asked

Viewed 147 times

1

My application manages courses, on my registration screen I have a field "amounts of vacancies", where, this is decreasing every time a student enrolls in a course. The problem now is that my Count is negatively the field "amounts of vacancies". On this screen I also have a field "Status" indicating if the course is available for enrolment, as I do for my field "amounts of vacancies" stop decreasing when arriving at zero and change the "Status" for Registrations Closed.

Action Registration

[HttpPost]
    public ActionResult Inscricao(int inscricaoId)
    {

        using (var scope = new TransactionScope())
        {
            Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
            if (aluno == null)
                return View("MeusCursos");

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

            var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Curso.Id == inscricaoId && ac.Aluno.Usuario == User.Identity.Name);
            if (alunoCurso != null)
                return RedirectToAction("Inscricao", "Curso");

            alunoCurso = new AlunoCurso
            {
                Aluno = aluno,
                Curso = curso
            };

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

            //Aqui é onde o Decremento acontece
            curso.Qtd_Vagas--;
            db.Entry(curso).State = EntityState.Modified;
            db.SaveChanges();

            scope.Complete();
        }

        return View(db.Cursos.ToList());
    }

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álago de Cursos</h2>

<table class="table table-hover">
    <tr>
        ...

        Status
        </th>
        <th>
            Quantidade de Vagas
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
           ...

           <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">
                    <input type="submit" value="Inscrição" name="detalhes" class="inscricao btn btn-success" data_toggle="modal" data_target="#modalaviso" data-inscricaoid="@item.Id" />
                    </div>
                </div>
            </td>
        </tr>

    }

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

    <a href="@Url.Action("Index", "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() {
                            $(this).attr("disabled", "disabled");
                        }
                });
            });
        });
    </script>

}

2 answers

1

Try this

    <table class="table table-hover">
    <tr>
        ...

        Status
        </th>
        <th>
            Quantidade de Vagas
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            ...

            <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>
                @if(item.Qtd_Vagas > 0){
                <div class="btn-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Inscrição" name="detalhes" class="inscricao btn btn-success" data_toggle="modal" data_target="#modalaviso" data-inscricaoid="@item.Id" />
                    </div>
                </div>
                }else{
                <div class="col-md-offset-2 col-md-10">Inscrições encerradas</div>
                }
            </td>
        </tr>

    }

</table>

1


Even though it is a screen behavior, it is important not to leave the Action decrease vacancies that do not exist:

[HttpPost]
public ActionResult Inscricao(int inscricaoId)
{

    using (var scope = new TransactionScope())
    {
        var aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
        if (aluno == null)
            return View("MeusCursos");

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

        if (curso.Qtd_Vagas <= 0) 
        {
            ModelState.AddModelError("", "Não existem mais vagas para este curso.");
            return RedirectToAction("MeusCursos");
        }

        var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Curso.Id == inscricaoId && ac.Aluno.Usuario == User.Identity.Name);
        if (alunoCurso != null)
            return RedirectToAction("Inscricao", "Curso");

        alunoCurso = new AlunoCurso
        {
            Aluno = aluno,
            Curso = curso
        };

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

        //Aqui é onde o Decremento acontece
        curso.Qtd_Vagas--;
        db.Entry(curso).State = EntityState.Modified;
        db.SaveChanges();

        scope.Complete();
    }

    return View(db.Cursos.ToList());
}

Plus, I’ve changed a little bit @joaoeduardorf’s solution to the View:

@foreach (var item in Model)
{
    <tr>
        ...

        <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">
                    @if (item.Qtd_Vagas > 0) {
                    <input type="submit" value="Inscrição" name="detalhes" class="inscricao btn btn-success" data_toggle="modal" data_target="#modalaviso" data-inscricaoid="@item.Id" />
                    } else {
                    <input type="submit" value="Não há vagas" name="detalhes" class="inscricao btn btn-default" disabled="disabled" />
                    }
                </div>
            </div>
        </td>
    </tr>

}
  • My Modelstate.Addmodelerror("", "There are no more vacancies for this course."); did not display the message in view @Gypsy

Browser other questions tagged

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