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
var, object instead of dynamic => the same resultRazor engine
Why I can't access the property, if the debugger can see it, and how can I solve this problem ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With