Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Base ViewModel in Asp.net MVC 2

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?

like image 769
Picflight Avatar asked May 01 '10 19:05

Picflight


1 Answers

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 )
    {
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
             var baseModel = result.Model as BaseViewModel;
             if (baseModel != null)
             {
                 baseModel.SiteID = ...
             }
        }
    }
}
like image 70
tvanfosson Avatar answered Sep 29 '22 21:09

tvanfosson