Search code examples
asp.net-mvc-3webgrid

Present multiple IEnumberables and single value properties in single webgrid


I have an Inventory Class that contains not only its own fields but several reference IDs to other classes.

public class Inventory {

  public int Id { get; set; }

  public string RtNum { get; set; }

  public string AcntNum { get; set; }

  public string CardNum { get; set; }

  public string Num { get; set; }

  [Range(1,3)]
  public int Type { get; set; }

  public int CompanyId { get; set; }

  public int BranchId { get; set; }

  public int PersonId { get; set; }   }

In my action I generate several IEnumerable lists of the relevant fields from the other classes. I also have several non-list values I want to pass to the View. I know how to create a ViewModel to pass everything to the webgrid but have no way of iterating through the lists. I also know how to AutoMap an index to one list, see How to display row number in MVC WebGrid. How would you combine the two so that you could use the index to iterate through multiple lists?

Update #1 (more detail)

public class Company {
  public int Id { get; set; } 
  public string Name { get; set; }   }

public class Branch {
  public int Id { get; set; } 
  public string Name { get; set; }   }

public class Person  {
  public int Id { get; set; } 
  public string Name { get; set; }   }

public class MyViewModel  {
  public int PageNumber { get; set; }
  public int TotalRows { get; set; }
  public int PageSize { get; set; }
  public IEnumerable<Inventory> Inventories { get; set; }
  public int Index { get; set; }
  public IEnumerable<string> CmpNm { get; set; }
  public IEnumerable<string> BrnNm { get; set; }
  public IEnumerable<string> PrnNm { get; set; }        }

Controller

public class InventoryController : Controller
{  // I have a paged gird who’s code is not relevant to this discussion but a pagenumber,
   //  pagesize and totalrows will be generated
   private ProjectContext _db = new ProjectContext();

   public ActionResult Index()  {
     IEnumerable<Inventory> inventories = _db.Inventories;
     List<string> cmpNm = new List<string>; List<string> brnNm = new List<string>; List<string>     prnNm = new List<string>;
     foreach (var item in inventories) { string x1 = ""; 
     Company cmps = _db. Company.SingleOrDefault(i => i.Id == item.CompanyId); if (cmps!= null)
      { x1 = cmps.Name; } cmpNm.Add(x1); x1 = "";
     Branch brns = _db. Branch.SingleOrDefault(i => i.Id == item. Branch Id); if (brns!= null) { x1 = brns.Name; } brnNm.Add(x1); x1 = "";
     Person pers = _db.Persons.SingleOrDefault(i => i.Id == item. PersonId);
      if (pers!= null) { x1 = pers.Name; } prnNm.Add(x1); 

     // the MyViewModel now needs to populated with all its properties and generate an index
     // something along the line of 
     new MyViewModel { PageNumber= pagenumber, PageSize= pagesize,  TotalRows=Totalrows, Inventories = inventories;  CmpNm=cmpNm, BrnNm=brnNm, PrnNm=prnNm}

View (How to create the Index is the problem)

@model.Project.ViewModels.MyViewModel
@{ var grid = new WebGrid(Model.Inventories, Model.TotalRows, rowsPerPage: Model.PageSize); }
@grid.GetHtml( columns: grid.Columns( 
    Grid.Column(“PrnNm”, header: "Person", format: @Model.PrnNm.ElementAt(Index))
    Grid.Column(“BrnNm”, header: "Branch", format: @Model.BrnNm.ElementAt(Index))
    Grid.Column(“CmpNm”, header: "Company", format: @Model.CmpNm.ElementAt(Index))
    grid.Column("RtNum", header: "Route"), 
    grid.Column("AcntNum", header: "Account"), 
    grid.Column("CardNum", header: "Card")
    …      )    )

What the grid should look like is self-evident.


Solution

  • It's pretty unclear what is your goal. But no matter what it is I would recommend you to define a real view model reflecting the requirements of your view and containing only the information you are interested in seeing in this grid:

    public class InventoryViewModel
    {
        public int Id { get; set; }
        public string PersonName { get; set; }
        public string BranchName { get; set; }
        public string CompanyName { get; set; }
        public string RouteNumber { get; set; }
        public string AccountNumber { get; set; }
        public string CardNumber { get; set; }
    }
    

    Now you could have the main view model:

    public class MyViewModel
    {
        public int PageNumber { get; set; }
        public int TotalRows { get; set; }
        public IEnumerable<InventoryViewModel> Inventories { get; set; }
    }
    

    Alright, the view is now obvious:

    @model MyViewModel
    
    @{ 
        var grid = new WebGrid(
            Model.Inventories, 
            rowsPerPage: Model.PageSize
        ); 
    }
    
    @grid.GetHtml( 
        columns: grid.Columns( 
            grid.Column("Id", header: "Inventory id"),
            grid.Column("PersonName", header: "Person"),
            grid.Column("BranchName", header: "Branch"),
            grid.Column("CompanyName", header: "Company"),
            grid.Column("RouteNumber", header: "Route"), 
            grid.Column("AccountNumber", header: "Account"), 
            grid.Column("CardNumber", header: "Card")
        )    
    )
    

    Now all that's left is build this view model in your controller. Since I don't know what you are trying to achieve here, whether you need an inner join or a left outer join on those columns, I will take as an example here a left outer join:

    public ActionResult Index()
    {
        var inventories = 
            from inventory in _db.Inventories
            join person in _db.Persons on inventory.PersonId equals person.Id into outerPerson
            join company in _db.Companies on inventory.CompanyId equals company.Id into outerCompany
            join branch in _db.Branch on inventory.BranchId equals branch.Id into outerBranch
            from p in outerPerson.DefaultIfEmpty()
            from c in outerCompany.DefaultIfEmpty()
            from b in outerBranch.DefaultIfEmpty()
            select new InventoryViewModel
            { 
                PersonName = (p == null) ? string.Empty : p.Name,
                CompanyName = (c == null) ? string.Empty : c.Name,
                BranchName = (b == null) ? string.Empty : b.Name,
                Id = inventory.Id,
                AccountNumber = inventory.AcntNum,
                CardNumber = inventory.CardNum,
                RouteNumber = inventory.RtNum
            };
    
    
        var model = new MyViewModel
        {
            PageSize = 5,
            // TODO: paging
            Inventories = inventories.ToList()
        };
    
        return View(model);
    }
    

    And that's pretty much it. Of course in this example I am leaving the pagination of the Inventories collection for you. It should be pretty trivial now to .Skip() and .Take() the number of records you need.

    As you can see ASP.NET MVC is extremely simple. You define a view model to reflect the exact requirements of what you need to show in the view and then populate this view model in the controller. Most people avoid view models because they fail to populate them, probably due to lack of knowledge of the underlying data access technology they are using. As you can see in this example the difficulty doesn't lie in ASP.NET MVC at all. It lies in the LINQ query. But LINQ has strictly nothing to do with MVC. It is something that should be learned apart from MVC. When you are doing MVC always think in terms of view models and what information you need to present to the user. Don't think in terms of what you have in your database or wherever this information should come from.