asp.net MVC3 + Entity Framework project, passing anonymous objects from the controller to the view is very common, originally thought dynamic can be easily done, finally found I was wrong:
Controller:
| The code is as follows |
Copy Code |
|
Public ActionResult Index ()
{
TestContext context = new TestContext ();
Dynamic Data = context. People
. Join (context. Pets, person => person. Id, Pet => pet.pid, (person, Pet) => new {person = person. Name, pet = pet. Name});
return View (data);
}
View:
@model Dynamic
@foreach (var item in Model)
{
@ (item. person) <text>,</text>@ (item. Pet) <br/>
} |
The reason for this is that the C # compiler always compiles anonymous types into internal, and throws an exception when a member that is not visible in the current context is accessed through dynamic. Problem Recurrence:
| The code is as follows |
Copy Code |
|
Using System;
Using System.Collections.Generic;
Using System.Linq;
Namespace Controller
{
public class Test
{
<summary>
Impersonate an anonymous object anonymous class
</summary>
Private Class Anonymous
{
public string Person {get; set;}
public string Pet {get; set;}
}
Public dynamic GetValue ()
{
return new Anonymous ();
}
}
}
Namespace View
{
Using Controller;
Class Program
{
static void Main (string[] args)
{
Dynamic anonymous = new Test (). GetValue ();
Console.WriteLine (anonymous. person);
Console.readkey ();
}
}
}
|
Used to solve the old Zhao's Todynamic method, today in the System namespace of the. NET 4.0 to see a class tuple, understand that it can also solve the problem above:
Controller:
| code is as follows |
copy code |
|
Public ActionResult Index ()
{
TestContext context = new TestContext ();
Dynamic Data = context. People
. Join (context. Pets, person => person. Id, Pet => pet.pid, (person, Pet) => new {person = person. Name, pet = pet. Name})
. ToList (). Select Item => tuple.create (item. Person, item. Pet));
return View (data);
}
View:
@model ienumerable<tuple<string, string>>
@foreach (var item in Model)
{
@ (item. ITEM1) <text>,</text>@ (item. ITEM2) <br/>
} |