0

I've been trying to get a better grasp on Model and ViewModel design. And for most of you out there, this is probably a silly question. For starters, here is my model:

public class Cities
{
    [Key]
    public int CityID { get; set; }
    public string City { get; set; }
    public int Miles { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

Now, when I create my ViewModel within my presentation layer, can I just use IEumerable<> to pass all records within my Cities table:

public class CitiesViewModel
{
    public IEnumerable<Cities> Cities { get; set; }
}

And then I could loop through all records with my Controller:

    [HttpGet]
    public ActionResult List()
    {
        CitiesViewModel model = new CitiesViewModel
        {
            Cities = repository.Cities
            .OrderBy(p => p.City)
        };
        return View(model);
    }

Or, should I just pass in the only data I want my View to have access to:

public class CitiesViewModel
{
    //public IEnumerable<Cities> Cities { get; set; }

    public string City { get; set; }
    public string State { get; set; }
}
JoshYates1980
  • 3,476
  • 2
  • 36
  • 57
  • 1
    Check [one.beat.consumer's answer here](http://stackoverflow.com/questions/8735466/fat-model-thin-controller-vs-service-layer), it should give you an idea. – MJVC Jul 07 '14 at 21:07
  • 2
    I think the purists would argue that the latter is the better choice, but I find both acceptable. – itsme86 Jul 07 '14 at 21:07
  • 1
    Yeah, view models are supposed to provide only the information needed by the view. – MJVC Jul 07 '14 at 21:09
  • @MarcosVqzdeRdz Thanks for the reference. Great info! – JoshYates1980 Jul 07 '14 at 21:37

2 Answers2

2

You can do:

class CityViewModel
{
    public string City { get; set; }
    public string State{ get; set; }
}

and then:

class CitiesViewModel
{
    public IEnumerable<CityViewModel> Cities { get; set; }
}
MJVC
  • 497
  • 4
  • 7
  • 1
    I actually prefer to bind the `IEnumerable<>` to the view rather than creating a class that only holds a collection of the first viewmodel. e.g. `@model IEnumerable` – Rohrbs Jul 07 '14 at 23:11
  • Me too, but Im not sure if thats the only information needed in the view. – MJVC Jul 08 '14 at 13:33
0

That depends of what do you want display on your view. If details of one City use :

public class CitiesViewModel
{


    public string City { get; set; }
    public string State { get; set; }
}

but if you want to display list of cites use :

public class CitiesViewModel
{
    public IEnumerable<Cities> Cities { get; set; }
}
sylwester
  • 16,498
  • 1
  • 25
  • 33