Bird Stream

Entrepreneurship, development and (sometimes) cycling, often simultaneously, mainly in Nottingham

Base View Model in ASP.NET MVC

I needed to reference some user context variables from within my site master page that had some logic behind their retrieval.

In this example I need to choose the display language for a user.

  1. Check cookie present indicating user’s language preference
  2. if not use HTTP language header
  3. if not use the application default language

The pattern I’ve ended up using is to implement a base view model from which all my specific view models inherit as follows:

public class BaseViewModel {     
    public string UserLanguage     
    {      
       get      
       {          
           return HttpContext.Current.Request.Cookies["language"] != null        
               ? HttpContext.Current.Request.Cookies["language"].Value           
               : CultureInfo.CurrentCulture.TwoLetterISOLanguageName;     
        }
    } 
}

 

I then use the generic class for the master page

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<BaseViewModel>" %>

Which then allows me to reference the model in the master page and keep the logic for deciding the language to display centralised.

Not sure I’m wholly happy with the inheritance as it adds a level of dependencies which smells a bit off but in the small application I’m working in it was easy to implement and does what I need.

Comments