我不知道如何实现这一目标。我想在视图中使用foreach循环以表格格式显示数据。此数据将来自linq查询,该查询使用3-4个表并选择要显示的不同字段。不知道如何返回这个,因为我得到一个匿名类型错误。
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
};
我的模型必须声明什么才能传递给视图?
答案 0 :(得分:5)
视图适用于视图模型,因此首先定义一个:
public class CustomerViewModel
{
public int ResponseId { get; set; }
public string CustomerFirstName { get; set; }
public string CustomerLastName { get; set; }
public string CustomerTestimonial { get; set; }
}
然后:
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>
现在你可以 loop 使用这个视图模型的显示模板向用户展示信息:
@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>