Validationsummary - Asp.Net MVC problems

Asked

Viewed 1,180 times

4

I’m having problems with Validationsummary in my application that manages Courses, I have a screen where the student enrolls in a course and in case he tries to enroll in it course again should appear the message Student is already enrolled in the course. Only this message is not showing up on 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>

}

  • When inspecting HTML, the message is written inside it?

  • No @Gypsy, nothing appears.

  • @Newbie is why you use Redirecttoaction, and do not return a model to that View, how will you add a modelState if you do not return a model ?

2 answers

1

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

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

And in his View you call the message if the error occurs. Follow an example:

Editing

//A mensagem de error será apresentada aqui
@TempData["MensagemErro"]
  • It didn’t work @Randrade. The if of the timeData I can put anywhere in the View?

  • @Beginner the if is simply not to display the class if there is no message. In this example I am using a class from Bootstrap. The important thing is you leave in your View the code: @TempData["MensagemErro"]. I edited the answer, test that way

  • Nothing @Randrade, I don’t know why you’re not showing up.

  • When debugging, he is entering the if and filling the TempData?&#Remembering that you are returning to the Action Inscription, logo the TempData should be in the View corresponding. E just to clarify. You’re just wanting to return the message to the View, correct?

  • What I need is the following, when the "student" click the registration button and he is already enrolled should appear the message that he is already registered in the course. Got it?!

1


Notice that:

@Html.ValidationSummary(true)

I don’t know if you ever pressed Ctrl + Shift + Space to see what that is true there:

Code Completion

excludePropertyErrors excludes any and all errors related to properties, including those that are defined with the empty property (your case). Switch to:

@Html.ValidationSummary(false)

This solution works if you want to print the error messages at the top of the page. In your case, you are setting by property:

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

In this case, the correct is to use:

@Html.ValidationMessageFor(model => model.Qtd_Vagas)
  • Nothing @Gypsy, still did not present the message on the screen.

Browser other questions tagged

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