2011-02-18 27 views
1

我不知道如何实现这一点。我想在我的视图中使用foreach循环以表格格式显示数据。这些数据来自linq查询,它使用3-4个表格并选择不同的字段进行显示。不知道如何返回这个,因为我得到一个匿名类型的错误。我该如何使用这个linq查询来显示数据在MVC中使用foreach循环

var info = from s in context.LennoxSurveyResponses 
         join customers in context.Customers on s.SurveyCode equals customers.SurveyCode 
         join lists in context.CustomerLists on customers.ListId equals lists.ListId 
         join dealer in context.Channels on lists.ChannelId equals dealer.ChannelId 
         where dealer.ChannelId == id 
         select new 
         { 
          ResponseId = s.ResponseId, 
          CustomerFirstName = customers.FirstName, 
          CustomerLastName = customers.LastName, 
          CustomerTestimonial = s.Question5Answer 
         }; 

什么将我的模型必须声明,这样可以传递给查看?

回答

5

视图可与视图模型,所以通过定义一个开始:

​​

然后:

public ActionResult Foo(string id) 
{ 
    var info = 
     from s in context.LennoxSurveyResponses 
     join customers in context.Customers on s.SurveyCode equals customers.SurveyCode 
     join lists in context.CustomerLists on customers.ListId equals lists.ListId 
     join dealer in context.Channels on lists.ChannelId equals dealer.ChannelId 
     where dealer.ChannelId == id 
     select new CustomerViewModel 
     { 
      ResponseId = s.ResponseId, 
      CustomerFirstName = customers.FirstName, 
      CustomerLastName = customers.LastName, 
      CustomerTestimonial = s.Question5Answer 
     }; 
    return View(info); 
} 

终于有你的观点被强类型到:

@model IEnumerable<CustomerViewModel> 

现在您可以 循环 使用此视图模型的显示模板预先发送的信息给用户:

@Html.DisplayForModel() 

和内部相应的显示模板(~/Views/Home/DisplayTemplates/CustomerViewModel.cshtml):

@model CustomerViewModel 
<div> 
    <span>First name: @Html.DisplayFor(x => x.CustomerFirstName)</span> 
    <span>Last name: @Html.DisplayFor(x => x.CustomerLastName)</span> 
    ...  
</div> 
+0

抱歉response..i晚是出城,不能查看您的意见,直到今天早上。谢谢!! – bladerunner 2011-02-21 14:47:09

相关问题