如下写法首先一个Student的classpublic class Student
{
public Int32 Id { get; set; }
public String Name{ get; set; }
}然后在一个Index视图控制器中 如下:public ActionResult Index()
{
var result=from s in DataContext.Student where s.Sex==0 select new {Id=s.Id,Name=s.Name};
//foreach(var obj in result)
//{ Response.Write(obj.Id); }这里用foreach是可以看到匿名类的属性的 ViewData["stuList"]=result; //至于写成 result.GetEnumerator() 或result.ToList<Stu>()可以随意 return View();
}问题出现,在Index视图中如何foreach获取匿名类的属性...排除foreach然后Obj.GetType().GetProperty("Id").GetValue(obj,null).ToString();这样的反射方法求解...
{
public Int32 Id { get; set; }
public String Name{ get; set; }
}然后在一个Index视图控制器中 如下:public ActionResult Index()
{
var result=from s in DataContext.Student where s.Sex==0 select new {Id=s.Id,Name=s.Name};
//foreach(var obj in result)
//{ Response.Write(obj.Id); }这里用foreach是可以看到匿名类的属性的 ViewData["stuList"]=result; //至于写成 result.GetEnumerator() 或result.ToList<Stu>()可以随意 return View();
}问题出现,在Index视图中如何foreach获取匿名类的属性...排除foreach然后Obj.GetType().GetProperty("Id").GetValue(obj,null).ToString();这样的反射方法求解...
要不就不使用匿名函数Controller: [HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
List<Student> array = new List<Student>();
array.Add(new Student(){Id = 10, Name = "aaa"});
array.Add(new Student() { Id = 11, Name = "bbb" });
array.Add(new Student() { Id = 12, Name = "ccc" });
array.Add(new Student() { Id = 13, Name = "dddd" }); ViewData["Array"] = from s in array select s;
return View();
}
View: <p> <% foreach (var one in (IEnumerable<MvcApplication2.Controllers.Student>)ViewData["Array"]) { %></p>
<h1> <%=one.Id %> - <%=one.Name %> </h1>
<% } %>
使用保存JSON到ViewData,each遍历
{
var result=from s in DataContext.Student where s.Sex==0 select new {Id=s.Id,Name=s.Name};
return View(result);
}
View中:<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
这样遍历:
<%foreach(var std in Model){%>
编号:<%:std.Id%></br>
姓名:<%:std.Name%>
<%}%>不过你既然定义了Student类,那就没必要使用匿名对象,可以直接使用Student,这样的话不是.net framework 4.0也可以运行,象这样:Controller中:public ActionResult Index()
{
var result=(from s in DataContext.Student where s.Sex==0 select s).ToList();
return View(result);
}
View中:<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<Student>>" %>
这样遍历:
<%foreach(Student std in Model){%>
编号:<%:std.Id%></br>
姓名:<%:std.Name%>
<%}%>
在控制器中我只需要两个呈现到视图,别的不想要,才选择匿名类...若通过已定义Student去遍历,那所有具有Id Name的类都可以当作foreach的类型去遍历,
而如果linq查找返回的匿名类 Id不叫Id了,叫StuId,Name叫StuName 这样Student就无法遍历了...看了大家的回答,我思考后可以扩展如下的方法
foreach(typeof(new{Id,Name}) stu in (IEnumerator)ViewMode["StuList"]) 其实还是反射...3楼大哥意思可能是转到客户端处理...
http://blog.csdn.net/wz361790599/archive/2010/08/22/5829590.aspx
http://blog.zhaojie.me/2010/05/asp-net-mvc-dynamic-view-model-binding-error-with-anonymous-types.html