Retrieve property from a dynamic object after stor

2019-05-02 00:54发布

问题:

In my MVC Application:

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'

The 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;

In my view

// 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.
}

Note

  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

Why I can't access the property, if the debugger can see it, and how can I solve this problem ?

回答1:

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.