【问题标题】:session become null in controller method会话在控制器方法中变为空
【发布时间】:2015-11-05 10:23:26
【问题描述】:

我有以下控制器,在该控制器中我创建了会话以保存 IENUMERABLE 数据集

    [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);
    }

编辑:

Create_Brchure 视图页面有 href 链接,可以在同一个类文件中调用 PrintIndex 方法

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

这是PrintIndex 方法

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

我想在Create_Brochure_PDF控制器方法中再次使用那个会话列表数据集,所以我在这里创建了那个方法

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

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

        return View(samplePDF);
    }

但在上述方法中,我得到了 null IEnumerable&lt;ProductsPropertiesVM&gt; newmodel

编辑:

如果我解释整个场景

  1. Create_Brochure控制器方法有视图,
  2. 在该视图中,我有 href 链接将 Create_Brochure 视图保存为 PDF
  3. 单击该 href 链接后,我将调用 PrintIndex 方法,因此 该操作方法再次调用Create_Brochure_PDF 方法, 所以我在Create_Brochure_PDF 中设置了空对象

【问题讨论】:

  • 在添加到会话之前,您确定在newmodel 中有数据
  • 如果您在调试时使用 ExpressIIS,每次启动后会话都会被终止。在点击Create_Brochure_PDF之前,您确定每次都点击Create_Brochure吗?
  • @RahulNikate 是的,一旦我调试了这个,我可以看到在Create_Brochure 方法中分配给IEnumerable&lt;ProductsPropertiesVM&gt; newmodel 的模型值但是我可以看到IEnumerable&lt;ProductsPropertiesVM&gt; newmodelCreate_Brochure_PDF 中也变成null跨度>
  • @Rob ,是的,它的原始流程是Create_Brochure 然后Create_Brochure_PDF 我正在使用IIS10
  • @Rob 如果我解释整个场景 1.Create_Brochure 控制器方法有一个视图,2.在那个视图中我有 href 链接将 Create_Brochure 视图保存为 PDF 3.一旦我点击该链接我正在调用PrintIndex 方法,因此在该操作方法中再次调用Create_Brochure_PDF 方法,因此我在Create_Brochure_PDF 中设置了空对象

标签: c# asp.net-mvc session ienumerable rotativa


【解决方案1】:

我之前也遇到过同样的问题,所以我在 Rotativa 库中提出了解决方案ViewasPdf() 方法

单击该 href 链接后,您可以直接调用,但您必须为此方法创建一个视图,然后将其生成为 PDF

这里是步骤

  1. 为要生成为 PDF 的视图创建一个操作

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

    }

  2. 为该 Action 方法生成视图

  3. Create_Brochure_PDF()方法中用下面这行替换rerurn View();

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

  1. 现在调用Create_Brochure_PDF()方法如下 Create_Brochure 查看页面

&lt;a href="@Url.Action("Create_Brochure_PDF", "Brochure")"&gt;Download ViewAsPdf&lt;/a&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-02
    • 2013-01-27
    • 1970-01-01
    • 2023-03-14
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多