使用 IEnumerable<匿名类型>在动态类型视图中 [英] Using an IEnumerable&lt;Anonymous Type&gt; within Dynamic Type View

查看:42
本文介绍了使用 IEnumerable<匿名类型>在动态类型视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var s = myInventoryEntities.p_Forms().Select(i => new  { i.Customer, i.Order_ID }).Distinct().ToList();

ViewBag.MyData = s;

return View();

这给了我

    { Customer = "Bob", Order_ID = 2644550 }

在我的剃刀代码中

我遍历数据

@foreach ( var x in @ViewBag.MyData){
x.Customer // Does not exist! :(
}

请帮忙!

对象"不包含客户"的定义

'object' does not contain a definition for 'Customer'

推荐答案

ViewBag 数据的生命周期非常有限.您确定要通过设置 ViewBag 数据的相同操作方法访问此视图吗?

ViewBag data's life time is very limited. Are you sure you are coming to this view from the same action method where you set the ViewBag data ?

建议:尽量避免动态类型,例如 ViewData/ViewBag.坚持使用强类型可以让您的代码更具可读性/可维护性.

Suggestion : Try to Avoid Dynamic types liek ViewData/ViewBag. Sticking to Strongly typed makes your code much better readable/ maintainable.

如果你的域对象和你想显示的内容是一样的,就不用费心去创建一个ViewModel.否则创建一个视图模型

If your Domain object and What you want to display is same, do not bother about creating a ViewModel. else create a viewmodel

public class CustomerOrder
{
  public string CustomerName
  public int OrderID { set;get;}
  //other properties as relevant (to the view)
}

并返回它而不是 ViewBag

and return that instead of the ViewBag

public ActionResult GetOrders()
{

  var s = myInventoryEntities.p_Forms().
          Select(i => new  CustomerOrder {
                                           CustomerName= i.Customer, 
                                           OrderID=i.Order_ID
                                         }).Distinct().ToList();
  return View(s);
}

在视图中

@model IList<CustomerOrder>
@foreach ( var x in Model)
{
   <p>@x.Customer</p>
}

这篇关于使用 IEnumerable<匿名类型>在动态类型视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆