Linq join query displayed in MVC view

I'm trying to display a linq join query in a partial web view.

Here is my query within my controller:

public ActionResult InactiveUsers()
        {
            using (ModelContainer ctn = new ModelContainer())
            {
                DateTime duration = DateTime.Now.AddDays(-3);

                var inactive = from usrs in ctn.aspnet_Users
                               where usrs.LastActivityDate <= duration
                               join o in ctn.Groups on
                               usrs.UserId equals o.UserID
                               select new
                               {
                                   usrs.UserName,
                                   usrs.LastActivityDate,
                                   o.PrimaryPhoneNumber,
                               };

                return View(inactive.ToList());
            }

        }

What I'm a bit confused on is what to do next. I'm familiar with adding strongly typed views using models, but what happens in my case where I have a join query?

If anyone could point me in the right direction I'd be very grateful.

Thanks.

Answers


Instead of returning an IEnumerable of anonymous types, you could create a class for the join result and then create a model for it as normal:

            var inactive = from usrs in ctn.aspnet_Users
                           where usrs.LastActivityDate <= duration
                           join o in ctn.Groups on
                           usrs.UserId equals o.UserID
                           select new InactiveUser(usrs.UserName, usrs.LastActivityDate, o.PrimaryPhoneNumber);

With an InactiveUser class which has a constructor which takes a UserName, Date and PhoneNumber.


One solution is to use the "ViewModel" pattern. Instead of creating an anonymous type create a view model that contains the data you want to display. Simply populate that and pass it to your view.

When using this pattern we create strongly-typed classes that are optimized for our specific view scenarios, and which expose properties for the dynamic values/content needed by our view templates. Our controller classes can then populate and pass these view-optimized classes to our view template to use. This enables type-safety, compile-time checking, and editor intellisense within view templates.


Need Your Help

Specify how cmake creates visual studio project

c++ visual-studio-2010 cmake

I'm setting up cmake for my project and I've set up a testing project for it. When it generates my visual studio 2010 project I want to make it as the project I've had earlier.

Modify POST String From Modal jqGrid Add/Edit Form

jquery post jqgrid modal-dialog

I have a jqGrid-based application which currently retrieves data from my database and displays as intended in my grid. Inline editing is disabled; I am using modal forms for editing existing record...