Search code examples
asp.net-mvcrazormodel-view

Where is the BEST PRACTICES place to put a list of Countries in a MVC Application?


In a heavy enviroment application, we have Users, Locations, bla bla bla... and we use in many situations a call to a service where we retrieve the list of countries.

Where is the 'best practice' or 'proper way' to implement this. This method is called in several places and many objects has a List<CountryVO> property.

Specially considering using Razor views an often having to add this property to ModelViews

The solution is using DAL / BLL / SERVICE / UI[s] architecture.

Real Example:

public class User {
...
...
public List<DeliveryZoneVO> DeliveryZones {get;set;}
    public User() {
    ...
        DeliveryZones = service.GetDeliveryZones().ToList();
    }
}

The class DeliveryZoneVO comes from a webservice, so one property is

int IdCountry

The class User have a list of DeliveryZoneVO as presented on the class, the 'problem' here, is since it retrieves the data from a web service, I only have the ID of the country.

When I prepare the data in the controller to send to the View:

UserModelView userMV = new UserModelView();
userMV.user = service.GetUserById(1);
ViewData.Model = userMV;

BUT, inside userMV.user, I have DeliveryZones with a list of DeliveryZoneVO objects with IdCountries.

In the view, when I do (for example) :

@DisplayFor(m => m.user.DeliveryZones)

I want to show the Country Name, only have the ID. So i need a reference somewhere.. the question lies in where should that data needs to be placed that is considered BEST PRACTICES.

Is having in all modelview (in the case of the example, the UserModelView() the property Countries with a List ?


Solution

  • A good thing because this kind of issues is to have a BaseController class that derived from controller, and all the other controllers you have derived from it.

    in the BaseController put a static List<CountryVO> property with getter only, this way it will be initialized once and will be accessible to all of your's controllers and views(If you pass it with the ViewModel or ViewBag).


    Example:

    public class BaseController : Controller
    {
        private static List<CountryVO> _allCountries;
    
        public static List<CountryVO> AllCountries
        {
            get{ return _allCountries ?? _GetCountriesFromSomeWhere();}
        }       
    }
    
    public class HomeController : BaseController 
    {
        public ActionResult Index()
        {
            ViewBag.AllCountries  = this.AllCountries;          
            return View();
        }
    }