mvcrazortopdf Null Reference Exception on first click ASP.NEt (Session not retrieving properly)

74 views Asked by At

Im working on a program that downloads a pdf file using mvcrazortopdf. On the first click, it throws a NullReferenceException error. Here is my code:

Controller:(ReviewerController.cs)

    public ActionResult PicOrderPDF() //error on this line
    {
        PurchaseOrder req = (PurchaseOrder)Session["purchaseOrderData"];
        var date = String.Format("{0:yyyyMMdd}", DateTime.Now);

        return new PdfActionResult(req)
        {
            FileDownloadName = date + "-PurchaseOrder" + (req.PicID).ToString("D4") + ".pdf"
        };

    }
    [HttpPost]
    public ActionResult DownloadPdf(PurchaseOrder purchaseOrder)
    {
        Session["purchaseOrderData"] = purchaseOrder;
        return RedirectToAction("PicOrderPDF", "Reviewer");

    }

Model: (PurchaseOrder.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SampleProject.Models
{
    public class PurchaseOrder : Account
    {

       public int PicID { get; set; }
       public DateTime RequiredDate { get; set; }

    }
}

PicOrderPDF is the view of the pdf to be downloaded. I tried adding a breakpoint at the error line to check and turns out req is null.But after continuing and clicking download again, it downloads just fine. Sorry im new at this

1

There are 1 answers

3
Usman On BEST ANSWER

the problem was the first time the session was cleared which resolved with adding

protected void Session_Start()
 {

 }

in the Global.asax.cs you can also check this session variables lost between controllers action methods