开发者

how do i use this linq query to display data using foreach loop in MVC

I am not sure how to achieve this. I want to use a foreach loop in my view to display the data in a tabular format. This data will come from a linq query that uses 3-4 tables and selects different fields to display. Not sure how to return this as i get an anonymous type error.

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
               开发者_C百科        select new
                       {
                           ResponseId = s.ResponseId,
                           CustomerFirstName = customers.FirstName,
                           CustomerLastName = customers.LastName,
                           CustomerTestimonial = s.Question5Answer
                       };

What would my model have to declare so that can be passed to view?


A view works with view models, so start by defining one:

public class CustomerViewModel
{
    public int ResponseId { get; set; }
    public string CustomerFirstName { get; set; }
    public string CustomerLastName { get; set; }
    public string CustomerTestimonial { get; set; }
}

and then:

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);
}

and finally have your view being strongly typed to:

@model IEnumerable<CustomerViewModel>

now you can loop use a display template with this view model to present the information to the user:

@Html.DisplayForModel()

and inside the corresponding display template (~/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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜