0

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.

Community
  • 1
  • 1
Joe
  • 4,143
  • 8
  • 37
  • 65
  • I don't understand your question. Please show your view model as well as the controller action that is populating it. What you have shown here is your domain model which is of very little interest for the WebGrid since you are passing a view model to the view. Also provide an example of how do you expect the table to look like. – Darin Dimitrov Oct 11 '12 at 16:19
  • @DarinDimitrov Have you been able to take a look, do you need anything else? Thanks – Joe Oct 15 '12 at 20:53

1 Answers1

2

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I'm already using ViewModels (partially from reading all your other posts) and have the concept of separation of concerns. What you have added here is that the ViewModels are simply a class that can be nested within each other and that leveraging Linq is a much better way to fill the Model. I see you added the ID field, I don't know if that was out of habit, a philisophical preference or for illustration purposes. Since it is an internal DB number and not of relevance to the user I tend not to display it, though it obviously has value as a troubleshooting aid. continued... – Joe Oct 16 '12 at 18:16
  • continued... I prefer abbreviated field names but in the future will try to avoid them in posting of simplified project models for the sake of clarity. As always reading one of your posts is an eductation and always takes my coding skills to a new level. I very much appreciate the wonderful service you provide to the community. To summarize; an index is not needed, MVC is based on separation of concerns, make your ViewModels more focused to only what is needed in the view, ViewModels can be nested and leverage the power of Linq to populate your models. Thank you again. – Joe Oct 16 '12 at 18:16