Frage

I need to build some Web screens with classic MVC architecture, containing Index page (list all instances of my class), Details (Check details of my class), Edit (Edit class data) and Delete (delete class instance).

I´m using Viewmodel and Automapper. I´m in a doubt about the correct way to assing ViewModels and Automapper in that scenario, as the index will have a collection of class and each other view will have just one instance:

Proposes Codes:

OPTION1: ONE CLASS FOR EACH VIEW:

public class Person
{ 
     int id;
     string Name;
     int Age;
}

public class PersonViewModel
{
     int id;

     [Display(name = "Person name")] 
     string Name;

     [Display(name = "Person age")] 
     int Age;
}

public class PersonIndexViewModel
{
     List<PersonViewModel> Personlist;
}


PersonController:

{
    var personList = db.List(); // Get data from db

    PersonIndexViewModel indexview = new PersonIndexViewModel();

    foreach (var item in personList)
    {  
         var tempview = new PersonViewModel();
         Map.Create (...); << Here ? How ?

         indexview.PersonList.Add (tempview);
    }

    return view (indexview);
}

OPTION2: ONE VIEWMODEL:

public class Person
{ 
     int id;
     string Name;
     int Age;
}

public class PersonViewModel
{
     int id;

     [Display(name = "Person name")] 
     string Name;

     [Display(name = "Person age")] 
     int Age;
}

PersonController:

{
    var personList = db.List(); // Get data from db

    List<PersonViewModel> viewList = new List<PersonViewModel>();


    foreach (var item in personList)
    {  

         var tempview = new PersonViewModel();
         Map.Create (...) // Here ? How ??
         viewList.Add (tempView);
     }

    return view (viewList);

}

Is there something wrong if option 2? What would the best practices be on that case ? Thanks!

War es hilfreich?

Lösung

It's really up to you - best practice... well that depends. I worried about that a lot at the start but I really learned Best Practice is very subjective. We use AutoMapper extensively and as a general rule we have a 1-1 map with View and ViewModel.

However if an Index contains no additional properties we often just return an IEnumerable<PersonViewModel> etc. However we often find we then do have to put in a ViewModel for the Index as soon as we need additional properties e.g. Filters etc

Also if you want to map a list to a list just do:

var model=Mapper.Map<List<PersonViewModel>>(personList)

Don't Create Map in controller. Set that up in a class at App startup see this question.

Have a look at these articles on AutoMapper. This one is a bit old but it was inspiration to us when we started. This one from Jimmy Bogard outlines their initial approach (and he created AutoMapper). This is his thoughts on how he is doing MVC now with some mentions on AutoMapper usage

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top