我使用了ViewModel的List Instance从查询中收集数据并试图在View中显示。但是对象" CustomerVMlist"返回null但没有结果,customerlist显示4个查询结果。我的观点完全是空的。
public class CustomerVM
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Mobileno { get; set; }
public Nullable<System.DateTime> OrderDate { get; set; }
public Nullable<decimal> OrderPrice { get; set; }
}
索引功能
public ActionResult Index()
{
List<CustomerVM> CustomerVMlist = new List<CustomerVM>(); // to hold list of Customer and order details
var customerlist =(from Cust in db.Customers
join Ord in db.Orders
on Cust.CustomerID equals Ord.CustomerID
select new
{
Cust.Name,
Cust.Mobileno,
Cust.Address,
Ord.OrderDate, Ord.OrderPrice
}).ToList();
foreach (var item in customerlist)
{
CustomerVM VMOBJ = new CustomerVM();
VMOBJ.Name= item.Name;
VMOBJ.Mobileno = item.Mobileno;
VMOBJ.Address = item.Address;
VMOBJ.OrderDate = item.OrderDate;
VMOBJ.OrderPrice = item.OrderPrice;
}
return View(CustomerVMlist);// returns null
}
答案 0 :(得分:4)
您需要将项目添加到列表中
foreach (var item in customerlist) {
CustomerVM VMOBJ = new CustomerVM();
VMOBJ.Name= item.Name;
VMOBJ.Mobileno = item.Mobileno;
VMOBJ.Address = item.Address;
VMOBJ.OrderDate = item.OrderDate;
VMOBJ.OrderPrice = item.OrderPrice;
CustomerVMlist.Add(VMOBJ);
}
答案 1 :(得分:3)
您忘记在列表中添加您创建的对象。
foreach (var item in customerlist)
{
CustomerVM VMOBJ = new CustomerVM();
VMOBJ.Name= item.Name;
VMOBJ.Mobileno = item.Mobileno;
VMOBJ.Address = item.Address;
VMOBJ.OrderDate = item.OrderDate;
VMOBJ.OrderPrice = item.OrderPrice;
// after having set all the values you add the newly created object to the list.
CustomerVMlist.Add(VMOBJ);
}
你可以用更少的代码行完成同样的事情,如下所示:
public ActionResult Index()
{
var CustomerVMlist = (from Cust in db.Customers
join Ord in db.Orders
on Cust.CustomerID equals Ord.CustomerID
select new CustomerVM
{
Name = Cust.Name,
Mobileno = Cust.Mobileno,
Address = Cust.Address,
OrderDate = Ord.OrderDate,
OrderPrice = Ord.OrderPrice
}).ToList();
return View(CustomerVMlist)
}
如您所见,我们可以将结果投影到所需类型CustomerVM
,而无需循环遍历结果集(使用foreach
),逐个创建所需的对象并添加它们列表。