Q1:以下是什么更好的速记版本? Q2:如何在mvc3中将匿名类型传递给我的视图?
public ViewResult Index3()
{
List<T1> ls = new List<T1>();
ls.Add(new T1 { id = 1, title = "t1", val1 = 1, val2 = 2});
ls.Add(new T1 {id=2, title="t2", val1=3, val2=4});
ls.Add(new T1 { id = 3, title = "t3", val1 = 5, val2 = 6});
return View(ls);
}
(Q1)类似于?:
List<T1> ls = new List<T1>(
List<T1>(new { id = 1, title = "t1", val1 = 1, val2 = 2}
new { id = 2, title = "t2", val1 = 3, val2 = 4})
);
(Q2)类似于?:
public ViewResult Index3()
{
return View(List(new { id = 1, title = "t1", val1 = 1, val2 = 2 }
new { id = 2, title = "t2", val2 = 3, val2 = 4 }
);
}
然后在剃须刀视图中引用上述内容:
@model IEnumerable<Some Anonymous or Dynamic Model>
@item.id
@item.title
@item.val1
...
答案 0 :(得分:1)
Q1是一个偏好问题。由于编译器在内部创建了类似的代码,因此没有性能差异。
Q2是不可能的,您必须创建一个非匿名类型才能访问它。
答案 1 :(得分:1)
可以使用ViewBag将您的列表传递给视图。
答案 2 :(得分:0)
集合初始值设定项的编写方式如下:
List<T1> ls = new List<T1> {
new T1 { id = 1, title = "t1", val1 = 1, val2 = 2 },
new T1 { id = 2, title = "t2", val1 = 3, val2 = 4 },
new T1 { id = 3, title = "t3", val1 = 5, val2 = 6 }
};
创建隐式类型数组:
return View(new [] { new { id = 1, ... }, ... });
答案 3 :(得分:0)
这两个选项都不起作用,因为匿名类型是内部,剃刀视图被编译成一个单独的程序集。
请参阅: Dynamic view of anonymous type missing member issue - MVC3