简体   繁体   中英

ASP.NET MVC - ViewModel for Listing from 2 Models at Once

I have a scenario where a user will submit a form that contains information for 2 models (database tables): Users and Requests. The data will also need to be listed together joined by UserID, ie to list all Requests made by all users, or by a specific user. So I also need to output the data from both tables.

My solution was to create ViewModel called UserRequests which would contain both of these models, however I am stuck on the implementation. I am not sure if it should look like the following:

public class UserRequestModel {
    public User User1 { get; set; }
    public Request Request1 { get; set; }

To summarize, what the Index() function in the Controller will do, is get a query of requests by all users and list all fields from both tables (joined). So I need to somehow get the data from that query into the ViewModel to output it and have no idea how to set up the ViewModel in order to do so. Any insight would be appreciated. Thanks!

You can just use linq to join the two tables and then project the records to your target view model so something like:

  var res = 
    from u in Users
    join r in Requests on u.UserId equals r.UserId 
    select new UserRequestModel { User1 = u,  Request1 = r}; 

Are you using an ORM (eg Entity Framework) to map the database tables?

The ViewModel should designed to help you displaying data. I would suggest you to follow the rule 1 ViewModel per View. You should design first clearly how you want to represent the data in the view. I'm not sure if your ViewModel is exactly what you want to represent. Do you want to show 1 request and all the users related? or you want 1 user and all the requests related? Or you want many requests with many users related?

Depending on your need, you should create the ViewModel. Imagine you want 1 user and many Requests, then I would have a List of Requests inside the user class.

The only thing I can think of is what you will get is one User and one Request which in your post seams like you will get more than one.

I would change the properties to Lists, IEnumerables or Arrays depending on what you prefer and then when you are getting the posts from the database, make a ToList(), ToArray() or similar.

public class UserRequestModel {
  public List<User> Users { get; set; }
  public List<Request> Requests { get; set; }
}

And when fetching the data you use the extensionmethod you like.

var Users = dbcontext.Users.Where(x => x.ex == example).ToList()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM