UwakPeter
UwakPeter

Reputation: 341

how do i select from multiple table and return the result to the view mvc 5

i am trying to display the result from this query in my index view, but it is reporting error, i have tried to debug it, no success, i will appreciate if anyone could assist in letting me know where i have gone wrong.

    public ActionResult Index()
    {           
       var users =
        (from u in db.Users
                     join s in db.States
                         on u.StateId
                         equals s.StateId

                     join l in db.Lgas
                         on u.LgaId
                         equals l.LgaId
                     select new
                     {
                         u.Surname,
                         u.Firstname,
                         u.Othernames,
                         u.Email,
                         s.StateName,
                         l.LgaName
                     }).ToList();


        return View(users);
    }

Upvotes: 0

Views: 1838

Answers (1)

teo van kot
teo van kot

Reputation: 12491

You cant pass anonymous object to View because every property of anonymous object marked internal and Views are in a different namespace. Here is great explanation.

Use ViewModel - it's the best solution.

ViewModel example:

public class UserViewModel
{
   public string Surname { get; set; }
   public string Firstname { get; set; }
   public string Othernames { get; set; }
   public string Email { get; set; }
   public string StateName { get; set; }
   public string LgaName { get; set; }
}

Your Controller:

public ActionResult Index()
{           
   var users =
    (from u in db.Users
                 join s in db.States
                     on u.StateId
                     equals s.StateId

                 join l in db.Lgas
                     on u.LgaId
                     equals l.LgaId
                 select new UserViewModel
                 {
                    Surname =  u.Surname,
                    Firstname = u.Firstname,
                    Othernames = u.Othernames,
                    Email = u.Email,
                    StateName = s.StateName,
                    LgaName = l.LgaName
                 }).ToList();


    return View(users);
}

And at the begin of your View:

@model List<YourViewModelNamespase.UserViewModel>

Change YourViewModelNamespase to actual namespace of your UserViewModel class.

On your View, you can do with your data anything you want everything in Model property.

Upvotes: 1

Related Questions