Retrieving a property from a dynamic object after saving / retrieving it from the session

In my MVC application:

In the controller, I created a list of the dynamic type that is stored in the session. The view then tries 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 opinion

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

  • At the time of debugging, in the clock view, I see properties / values
  • I cannot save the list in the ViewBag in my case, because I used ajax to call the method
  • I tried using var, objectinstead of dynamic=> the same result
  • I think this is not related to MVC or Razor engine
  • I tried using aspx view (not shaving) and the same result

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

+5
1

internal , . dynamic API . ( "//output..." ), , . /MVC 3 IIRC , - , - , /MVC 3/.NET/VS. , POCO:

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

. , dynamic, .

+4

All Articles