Setting Properties In Models With Strongly Typed Model Filters ASP.Net MVC C#

Page content

I like strongly typed view models in MVC. Typical structure of my site in Razor View Engine includes a page base model that is used in the Layout template and then I use inheritance to add properties to each model or commonly re-used properties. There are various reasons why to avoid dynamic in your models, besides the fact that you cannot use dynamic in master frame using razor.

The problem with model properties instead of something like ViewBag is that your controllers and services can start to grow with logic that shouldn’t really be there.

There are various ways to deal with this, one of them is assigning the properties you want commonly in your view models using filters.

To make the life a bit easier. I wrote ModelFilterBase that looks for a specific model on result execution and triggers OnModelLoaded method, if the model is found.

Real world example

Lets say you want every view model to contain information about the browser that is used. We can create an interface and implement the interface on the view model.

 1public interface IBrowserDetails
 3    string BrowserName {get;set;}
 6//implement the interface on the model or model base
 7public class HomeModel : IBrowserDetails
 9    public string BrowserName {get;set;}
10    //... other properties

Then, implement the BrowserModelFilter with IBrowserDetails interface as type. Override the OnModelLoaded method and notice the protected model property with IBrowserDetails as type. Also, don’t forget to register the filter.

1public class PermissionModelFilter : PresentationModelFilterBase<IBrowserDetails>
3    protected override void OnModelLoaded(ResultExecutingContext filterContext)
4    {
5        var capabilities = filterContext.HttpContext.Request.Browser;
6        Model.BrowserName = capabilities.Browser;
7    }

The example above is a trivial. However, you can add complex logic or inject services into your filters.

The PresentationModelFilterBase Class

The implementation of the model filter base class:

 1public abstract class PresentationModelFilterBase<T> : ActionFilterAttribute where T : class
 2    {
 3        protected T Model;
 5        public override void OnResultExecuting(ResultExecutingContext filterContext)
 6        {
 7            base.OnResultExecuting(filterContext);
 9            Model = filterContext.Controller.ViewData.Model as T;
10            if (Model == null) return;
12            OnModelLoaded(filterContext);
13        }
15        protected abstract void OnModelLoaded(ResultExecutingContext filterContext);
16     }

You can download the whole sample below.