Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve property from a dynamic object after storing/retrieving it From the Session

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 ?

like image 555
amd Avatar asked Oct 07 '22 22:10

amd


1 Answers

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.

like image 149
Marc Gravell Avatar answered Oct 10 '22 02:10

Marc Gravell