session become null in controller method

2019-02-25 23:52发布

问题:

I have following controller , in that controller I created session to save IENUMERABLE data-set

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Create_Brochure(IEnumerable<ProductsPropertiesVM> model)
    {

        IEnumerable<ProductsPropertiesVM> newmodel = model;

        IEnumerable<BrochureTemplateProperties> sample = model.Where.....

        Session["TemplateData"] = newmodel;

        return View(sample);
    }

EDIT:

Create_Brchure View page has href link to call PrintIndex method in same class file

<a href="@Url.Action("PrintIndex", "Brochure")">Download ViewAsPdf</a>

this is PrintIndex method

    public ActionResult PrintIndex()
    {
        return new Rotativa.ActionAsPdf("Create_Brochure_PDF") { FileName = "TestActionAsPdf.pdf" };
    }

I want to use that session list dataset again in Create_Brochure_PDF controller method,so I created here that method

    public ActionResult Create_Brochure_PDF()
    {
        IEnumerable<ProductsPropertiesVM> newmodel = Session["TemplateData"] as IEnumerable<ProductsPropertiesVM>;

        IEnumerable<BrochureTemplateProperties> samplePDF = newmodel.Where(....

        return View(samplePDF);
    }

but in above method I'm getting null IEnumerable<ProductsPropertiesVM> newmodel

EDIT:

If I explain this whole scenario

  1. Create_Brochure controller method has a view ,
  2. In that view I have href link to save that Create_Brochure view as PDF
  3. Once I click that href link I'm calling PrintIndex method so in that action method again its calling to Create_Brochure_PDF method , so I'm getting null object set in Create_Brochure_PDF

回答1:

I had the same issue some times ago, So I came up with solution ViewasPdf() method in Rotativa library

You can directly call to once You click that href link but you have to create a View for this method that your going to generate as PDF

So here the steps

  1. Create a Action for the View that your Going to Generate as PDF

    public ActionResult Create_Brochure_PDF()
    {
    
        IEnumerable<ProductsPropertiesVM> newmodel = Session["TemplateData"] as IEnumerable<ProductsPropertiesVM>;
    
        IEnumerable<BrochureTemplateProperties> samplePDF = newmodel.Where(.... 
    
        rerurn View();
    

    }

  2. Generate view for that Action method

  3. Replace this line rerurn View(); with following line in Create_Brochure_PDF() method

return new Rotativa.ViewAsPdf("Create_Brochure_PDF") { FileName = "TestActionAsPdf.pdf" };

  1. Now call the Create_Brochure_PDF() method as follows in Create_Brochure view page

<a href="@Url.Action("Create_Brochure_PDF", "Brochure")">Download ViewAsPdf</a>