Problems filling out PDF fields in Asp.net MVC

Asked

Viewed 101 times

1

I’m in trouble to render some fields from my table in the file PDF. It was working fine, but I don’t know what happened to those fields are no longer rendering. On my screen My Courses, the pupil has a button that emits a Statement of Completion of Course, but when the student clicks on the button and generates the PDF the fields come data-free. Obs.: The data that should render in the PDF are: Student Name, Enrollment, Course Name, Period and Workload.

inserir a descrição da imagem aqui

View PDF

@model MeuProjeto.Models.AlunoCurso
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="~/Content/PDF.css" rel="stylesheet" type="text/css" />
    <title>GeraPDF</title>
</head>
<body>
    <br/> <br/>

    <div id="declaracao">
        <strong style="font-family: 'Times New Roman'">Declaração de Conclusão de Curso</strong>
    </div>

<br/>
<hr/>

<text style="font-family: 'Times New Roman'; font-size: 20px">
    Declaramos que o Sr(a). <b>@Html.DisplayFor(model => model.Aluno.Nome)</b>, matrícula de Nº <b>@Html.DisplayFor(model => model.Aluno.Matricula)</b>,
    inscrito no curso de <b>@Html.DisplayFor(model => model.Curso.Nome_Curso)</b>, na XXXXX,
    no período de <b>@Html.DisplayFor(model => model.Curso.Dt_Inicio)</b> a <b>@Html.DisplayFor(model => model.Curso.Dt_Fim)</b>,
    cumprindo uma carga horária de <b>@Html.DisplayFor(model => model.Curso.Carga_Horaria)</b>, com total comprometimento e dedicação todos os requisitos para a conclusão deste curso,
    estamos encaminhando esta via de Declaração para que seja emitido junta a XXXXXX, o
    <b>Certificado</b> de conclusão de Curso.
</text>

<hr/>

<div id="assinatura">
    _________________________ <span>em</span><span> ___/___/_____</span><br/>
    Assinatura do Responsável
</div>
</body>
</html>

Action PDF

public ActionResult GerarPDF(int id)
    {
        var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Aluno.Usuario == User.Identity.Name);
        if (alunoCurso != null)
        {
            AlunoCurso aluno =
                db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id);

            var pdf = new ViewAsPdf
            {
                ViewName = "GeraPDF",
                FileName = "Declaração.pdf",
                Model = aluno,
                PageSize = Size.A4,
                PageMargins = new Margins {Bottom = 2, Left = 2, Right = 2, Top = 2}
            };

            return pdf;
        }

        return View();
    }

Snippet from my View with the Call PDF button

@model IEnumerable<MeuProjeto.Models.AlunoCurso>

<!-- Aqui é BOTÃO onde chama a página do PDF -->

<div class="btn-group">
<div class="col-md-offset-2 col-md-10">
 @if (item.Aprovado == false)
  {
   <input type="submit" value="Pendente de Aprovação" name="meusCursos" class="cursos btn btn-primary btn-sm" disabled="disabled" data-id="@item.Id" />
  }
  else
  {
  <a href="~/AlunoCursos/[email protected]" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-print"></span></a>
  }
  </div>
  </div>

@section Scripts {
            @Scripts.Render("~/bundles/jqueryval")
            <script>
                $(document).ready(function () {
                    $(".cursos").click(function () {
                        $.ajax({
                            type: "POST",
                            url: "MeusCursos/",
                            data: { id: $(this).data("id") },
                            success: function () {
                                $(this).attr("enable", "enable");
                            }
                        });
                    });
                });
            </script>
  • Ever tried to put breakpoints in View to check the status of the Model?

  • I put @Ciganomorrisonmendez, it’s not bringing anything. The funny thing is that it was working, and now I don’t know what happened. Can help me?

2 answers

0


Be able to solve as follows: In my Action I changed nothing

public ActionResult GerarPDF(int id)
    {
        //Aqui eu pego o usuário logado
        var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Aluno.Usuario == User.Identity.Name);
        if (alunoCurso != null)
        {
            //Aqui eu faço o include do aluno e pego o AlunoID
            AlunoCurso aluno =
                db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id);

            var pdf = new ViewAsPdf
            {
                ViewName = "GeraPDF",
                FileName = "Declaração.pdf",
                Model = aluno,
                PageSize = Size.A4,
                PageMargins = new Margins {Bottom = 2, Left = 2, Right = 2, Top = 2}
            };

            return pdf;
        }

        return View();
    }

Here is the code of the button that calls the Action PDF

<div class="btn-group">
  <div class="col-md-offset-2 col-md-10">
   @if (item.Aprovado == false)
    {
      <input type="submit" value="Pendente de Aprovação" name="meusCursos" class="cursos btn btn-primary btn-sm" disabled="disabled" data-id="@item.Id" />
              }
              else
              {
                              <!-- Aqui nessa linha que DEVE SER FEITA A ALTERAÇÃO -->
               <a href="~/AlunoCursos/[email protected]" class="btn btn-success btn-sm">Emitir Declaração</a>
              }
              </div>

Change must be made in @item. Id, as needed to get the student ID the correct is to pass the Alunoid.

<div class="btn-group">
    <div class="col-md-offset-2 col-md-10">
     @if (item.Aprovado == false)
     {
      <input type="submit" value="Pendente de Aprovação" name="meusCursos" class="cursos btn btn-primary btn-sm" disabled="disabled" data-id="@item.Id" />
              }
              else
              {
                 <!-- Só trocar o @item.Id por @item.AlunoId -->
               <a href="~/AlunoCursos/[email protected]" class="btn btn-success btn-sm">Emitir Declaração</a>
              }
              </div>

This way the fields in the PDF will be filled in.

0

I’m not sure if that’s it, but don’t use it @Html.DisplayFor() with the Rotary. The Rotary is a weird and troublesome package. Switch to the direct mention of the variable, as below:

<text style="font-family: 'Times New Roman'; font-size: 20px">
    Declaramos que o Sr(a). <b>@Model.Aluno.Nome</b>, matrícula de Nº <b>@Model.Aluno.Matricula</b>,
    inscrito no curso de <b>@Model.Curso.Nome_Curso</b>, na XXXXX,
    no período de <b>@Model.Curso.Dt_Inicio</b> a <b>@Model.Curso.Dt_Fim</b>,
    cumprindo uma carga horária de <b>@Model.Curso.Carga_Horaria</b>, com total comprometimento e dedicação todos os requisitos para a conclusão deste curso,
    estamos encaminhando esta via de Declaração para que seja emitido junta a XXXXXX, o
    <b>Certificado</b> de conclusão de Curso.
</text>

EDIT

I think you are using the wrong key to select. Modify the code below:

AlunoCurso aluno =
            db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id);

To:

var alunoCurso =
            db.AlunoCursos.Include(a => a.Aluno).FirstOrDefault(ac => ac.AlunoCursoId == id);
  • I think the problem is here AlunoCurso aluno = db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id); why the pupil are coming null. But I couldn’t fix it.

  • @Newbie Please write a response, clarifying how it was done, for the benefit of the community?

  • I still can not fix the error @Gypsy debugar that the pupil of that code snippet AlunoCurso aluno = db.AlunoCursos.Include(a => a.Aluno).AsNoTracking().FirstOrDefault(al => al.AlunoId == id); is coming null, but I still don’t know why.

  • @Newbie I updated the answer. See if it fits you.

  • I did not give right @Ciganomorrisonmendez, because the statement should be issued by the user who is logged in, as I did here var alunoCurso = db.AlunoCursos.FirstOrDefault(ac => ac.Aluno.Usuario == User.Identity.Name);&#xA; if (alunoCurso != null). There inside the if he did not accept this passage.

  • What do you mean, "you didn’t accept this excerpt"? Be clearer. Don’t answer with "it didn’t work out". Say exactly what happened, with the error message. I don’t see your screen. Reading "didn’t work out" won’t make me help you with quality.

  • Keeps coming nulo @Gypsy.

Show 2 more comments

Browser other questions tagged

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