【问题标题】:create session for IEnumerable<> list and reuse that session in controller methods [duplicate]为 IEnumerable<> 列表创建会话并在控制器方法中重用该会话 [重复]
【发布时间】:2015-11-06 04:09:32
【问题描述】:

我得到IEnumerable&lt;object&gt; 列表到Create_Brochure 控制器方法如下

所以我想保留这个对象列表并在Create_Brochure_PDF控制器方法中重用

所以我在 create session 中添加了以下几行 在Create_Brochure控制器方法中

IEnumerable<ProductsPropertiesVM> newmodel = model;

Session["TemplateData"] = newmodel;

为了在Create_Brochure_PDF 控制器方法中使用该会话,我在Create_Brochure_PDF 控制器方法中添加了以下几行

IEnumerable<ProductsPropertiesVM> newmodel = Session["TemplateData"] as IEnumerable<ProductsPropertiesVM>;

但我在Create_Brochure_PDF 控制器方法中为这个新模型获得了null

我需要知道如何为IEnumerable&lt;object&gt; 列表定义一个会话并在另一个方法中正确地重用它。

【问题讨论】:

  • 试试这个IEnumerable&lt;ProductsPropertiesVM&gt; newmodel =(IEnumerable&lt;ProductsPropertiesVM&gt;)Session["TemplateData"];
  • 同样的事情,除了如果强制转换失败而不是 null,你会得到一个 InvalidCastException。
  • @EricJ。一旦我调试,我可以看到它的 null 不是我认为的演员问题
  • @kez:如果你的演员使用as语法无效,表达式产生null。
  • @EricJ。一旦我尝试您的方法'object' does not contain a definition for 'Cast' and the best extension method overload 'Queryable.Cast&lt;ProductsPropertiesVM&gt;(IQueryable)' requires a receiver of type 'IQueryable',就会出现这种编译时错误

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


【解决方案1】:

我觉得你的定义没有问题,

PrintIndex()Create_Brochure_PDF() 方法中添加以下行,并为 Create_Brochure_PDF() 控制器方法和 PrintIndex() 添加调试点,并找出它将为空的位置

IEnumerable<ProductsPropertiesVM> newmodel = Session["TemplateData"] as IEnumerable<ProductsPropertiesVM>;

【讨论】:

    【解决方案2】:

    试试这样:

    IEnumerable<ProductsPropertiesVM> newmodel =(IEnumerable<ProductsPropertiesVM>)Session["TemplateData"];
    

    因为如果使用 as 语法您的转换无效,则表达式将生成 null。

    [Reference#1][Reference#2]

    【讨论】:

    • 因此,您建议不要返回 null 来产生异常...不确定它如何解释 OP 观察到的行为。
    • @waqar 一旦我使用你的方法得到也为 null 这是截图s17.postimg.org/x6ev5jg33/saadsa.jpg
    • @waqar 我在Create_Brochure_PDF 中添加了您的代码行,我说对了吗
    • 你能发布你的完整代码吗?
    • @WaqarAhmed 这里是相关代码 sn-p bitbucket.org/snippets/Common_Admin/rLXR5
    猜你喜欢
    • 1970-01-01
    • 2019-04-17
    • 2013-09-04
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多