views:

94

answers:

1

Using ASP MVC and Entity Framework. In the view, you have a page declaration that specifies the model for this view will be a collection implementing IEnumerable. Let's say that collection holds Car objects, that are only from Ford (Ford being the Category).

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<detelete.Models.Car>>" %>

This list of Ford cars only, was generated via a LINQ to Entities query. The EF object thingee is aware of the relationship of Cars to Manufacturers (which I call the category)

            var dat = ent.CarSet.Where(m => m.Manufacturer.Name == nm);

        List<Car> cars = dat.ToList<Car>();
        return View("ListingByManufacturer", cars);

So, in the view I display the list of cars that are all Ford's. I have the view displaying all the cars properties correctly, but there isn't a way to show what category (manufacturer in this example) the cars are from. I have seen some EF/MVC examples that have two foreach loops, and the top one displays the manufacturer - but that feels klugey.

Seems like it should be simple, but I am stuck...

+2  A: 

You can just pass the Manufacturer name via ViewData in the controller :

ViewData["Manufacturer"] = nm;

Or use a another object as your model that holds both cars and the manufacturer name

public class CategoryViewModel {
     public string ManufacturerName { get; set; }
     public List<Car> Cars { get; set; }
}

And pass an instance of that class to the view.

çağdaş
I prefer the model option instead of muddying up ViewData with unnecessary strings. This would be a "ViewModel". They are separated from your actual data model, and exist solely to provide convenience to your view.
Peter J
ViewModel. That looks like a perfect fit for this problem. I have been telling myself, 'once you get a handle on asp.net mvc, you need to look into the current wars over Views and ViewModels'.
wyldebill