存储之后,从一个动态对象检索属性/检索它从会话 [英] Retrieve property from a dynamic object after storing/retrieving it From the Session

查看:122
本文介绍了存储之后,从一个动态对象检索属性/检索它从会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC应用程序:

In my MVC Application:

在控制器I创建的动态型,它是存储在会话的列表。
该视图然后试图访问的对象,但它抛出一个异常:'对象'不包含'A'

In the controller I created a list of dynamic type, which is stored in the session. The view then attempts to access the objects but it throws an exception : 'object' does not contain a definition for 'a'

在code:

// Controller 

List<dynamic> myLists = new List<dynamic>();
for(int i=0; i<3; i++){
    var ano = new { a='a' , b = i };
    myLists.Add(ano);
}

Session["rows"] = myLists;

在我看来

// My View
foreach( dynamic row in (Session["rows"] as List<dynamic>)){
    <div>@row</div> // output {a:'a', b :1}
    <div>@row.a</div> // throw the error.
}

注意


  1. 在调试的时候,在腕表认为我能看到的属性/值

  2. 我无法在ViewBag列表存储在我的情况,因为我用AJAX调用方法

  3. 我试图用 VAR 对象而不是动态 =>相同的结果

  4. 我认为这是不相关的MVC或剃刀引擎

  5. 我试图用一个ASPX视图(不是剃刀之一),相同的结果

  1. At the debug time, in the watch view I can see the properties/values
  2. I can't store the list in the ViewBag in my case because I used ajax to call the method
  3. I tried to use var, object instead of dynamic => the same result
  4. I think this is not related to MVC or Razor engine
  5. I tried to use a aspx view (not the razor one) and the same result

为什么我不能访问属性,如果调试器可以看到它,我怎么能解决这个问题?

推荐答案

匿名类型是内部来声明它们的装配。在动态 API 尊重辅助功能即可。由于该值是存在的(从//输出...),我必须结束这是一个辅助的问题。 IIRC早期建立剃刀/ MVC3曾与问题究竟这种情况下,虽然从内存问题的服务包之一就走了 - 你可能要检查你是最新的最新与剃刀/ MVC3 / .NET / VS补丁。然而,的最简单的修复,这里将是声明适当的POCO类:

Anonymous types are internal to the assembly that declares them. The dynamic API respects accessibility. Since the value is there (from "// output..."), I must conclude this is an accessibility issue. IIRC early builds of razor/MVC3 had an issue with exactly this scenario, although from memory that problem went away with one of the service packs - you might want to check you are up-to-date with razor / MVC3 / .NET / VS patches. However, the easiest fix here will be to declare a proper POCO class:

public class MyViewModelType {
    public char A {get;set;}
    public int B {get;set;}
}

和用它来代替匿名类型。这也意味着你不需要使用动态,这是不必要的,矫枉过正这里。

and use that instead of an anonymous type. This will also mean you don't need to use dynamic, which is unnecessary and overkill here.

这篇关于存储之后,从一个动态对象检索属性/检索它从会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆