views:

182

answers:

1

As I familiarize myself with Asp.Net MVC, I am using MVC 2, I have noticed the use of a BaseViewData class in the Kigg project which I am unsure how to implement.

I want each of my ViewModels to have certain values available. Using an iterface comes to mind but I am wondering what the best practice is and how does Kigg do it?

Kigg

public abstract class BaseViewData 
{ 
  public string SiteTitle { get; set; }
  // ...other properties
}
public class UserListViewData : BaseViewData
{
   public string Title { get; set; }
   // .. other stuff
}

In my WebForms application I use a BasePage that inherits from System.Web.UI.Page.
So, in my MVC project, I have this:

public abstract class BaseViewModel
{
    public int SiteId { get; set; }
}
public class UserViewModel : BaseViewModel
{
  // Some arbitrary ViewModel
}
public abstract class BaseController : Controller
{
    private IUserRepository _userRepository;

    protected BaseController()
        : this(
            new UserRepository())
    {
    }
 }

Referencing the Kigg methodology, how do I make sure that each of my ViewModel that inherits from the BaseViewModel have the SiteId property?

What is the best practice, samples or patterns I should be using?

+3  A: 

The approach that I would take is to use a base controller as well and use the OnActionExecuted override to populate your model with common data. Then just make sure that your controllers inherit from your base controller and your models inherit from the base model.

public class BaseController : Controller
{

    public override void OnActionExecuted( ActionExecutedContext filterContext )
    {
        if (filterContext.Result is ViewResult
            && filterContext.Result.ViewData.Model != null)
        {
             var baseModel = filterContext.Result.Model as BaseViewModel;
             baseModel.SiteID = ...
        }
    }
}
tvanfosson