Problems with ValidationSummary - Asp.Net MVC

3

I have problems with ValidationSummary in my application that manages Courses , I have a screen where the student enrolls in a course and if he tries to enroll in the same course the Student already enrolled in the course message should appear again. However, this message is not appearing in View for the student.

Action

    // GET
    public ActionResult Inscricao()
    {
        Aluno aluno = db.Alunos.FirstOrDefault(a => a.Usuario == User.Identity.Name);
        if (aluno == null)
            return View("MeusCursos");

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

    [HttpPost]
    public ActionResult Inscricao(int inscricaoId)
    {
        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");

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

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

            var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Curso.Id == inscricaoId && ac.Aluno.Usuario == User.Identity.Name);
            if (alunoCurso != null)
            {
                ModelState.AddModelError("alunoCurso", "Aluno já está inscrito no curso.");
                return RedirectToAction("Inscricao", "Curso");
            }

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

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

            curso.Qtd_Vagas--;
            db.Entry(curso).State = EntityState.Modified;
            db.SaveChanges();

            scope.Complete();
        }

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

View

@model IEnumerable<MeuProjeto.Models.Curso>

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

@Html.ValidationSummary(true)
<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="@Url.Action("Ementa", "Curso")" data_toggle="modal" data_target="#modalaviso">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">
                        @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>

    }

</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>

}

    
asked by anonymous 14.06.2015 / 06:31

2 answers

0

Notice that:

@Html.ValidationSummary(true)

I do not know if you ever pressed Ctrl + Shift + Space to check what that true ali:

excludePropertyErrorsexcludesanyerrorrelatedtoproperties,includingthosethataresetwiththeemptyproperty(yourcase).Changeto:

@Html.ValidationSummary(false)

Thissolutionworksifyouwanttoprinttheerrormessagesatthetopofthepage.Inyourcase,youaresettingbyproperty:

ModelState.AddModelError("Qtd_Vagas", "Não existem mais vagas para este curso.");

In this case, the correct one is to use:

@Html.ValidationMessageFor(model => model.Qtd_Vagas)
    
15.06.2015 / 22:47
1

You can work with TempData[""] to take this information. In this case, you would do this on your controller :

     if (curso.Qtd_Vagas <= 0)
                {
                    TempData["MensagemErro"] = "Não existem mais vagas para este curso.";
                    return RedirectToAction("Inscricao");
                }

And in your View you call the message in case the error occurs. Here is an example:

Editing

//A mensagem de error será apresentada aqui
@TempData["MensagemErro"]
    
15.06.2015 / 15:39