Mahmoud ElMansy: knowledge meant to be free

How To Assign Data To All Models Objects And Pass Common Data To View

First let’s answer this question.
In what order are filters executed in asp.net MVC?

Answer

1) Authorization filters.
2) Action filters.
3) Response filters.
4) Exception filters.

We will talk about Action Filters
We will find 4 override method when inherits this class “System.Web.Mvc.ActionFilterAttribute” and there order on execution is.

  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted

In this example we will use “OnActionExecuted
This action called after action Executed and will pass Model to view
Here is the complete code of the “ViewModelFilterAttribute.cs”

  public class ViewModelFilterAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        //this is a sample property that i can pass to this class
        public string Controller
        {
            get;
            set;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }
       
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            Debug.WriteLine("Inside OnActionExecuted");
            // disable caching for this request
            filterContext.HttpContext.Response.Cache.SetNoServerCaching();
            filterContext.HttpContext.Response.Cache.SetNoStore();
            bool isAuthorized = filterContext.HttpContext.User.Identity.IsAuthenticated;
           
            if (isAuthorized)
            {
                if (filterContext.RouteData.Values["controller"] != null &&
                    filterContext.RouteData.Values["action"] != null &&
                    filterContext.RouteData.Values["controller"].ToString().Trim().Length > 0 &&
                    filterContext.RouteData.Values["action"].ToString().Trim().Length > 0)
                {
                    string controller = Controller;
                   
                    if (string.IsNullOrEmpty(Controller))
                        controller = filterContext.RouteData.Values["controller"].ToString();
                   
                    string action = filterContext.RouteData.Values["action"].ToString();
                    if (action.ToLower() != "delete")
                    {
                        string username = filterContext.HttpContext.User.Identity.Name;

                        //here is the main part t o get the model that is passed to view
                        var model = filterContext.Controller.ViewData.Model;

                        try
                        {
                            //here we can assign any data to the model and pass it to view
                            //note this done here only and i don't need to write it all over in every action
                            ((MvcViewModelFilterAttribute.Models.CommonModel)model).SecurityClass = new Models.SecurityClass();

                            ((MvcViewModelFilterAttribute.Models.CommonModel)model).SecurityClass.UserName = username;
                        }
                        catch { }
                    }
               

                }

            }
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
        }
    }

To focus on our sample The most important part is .

 //here we can assign any data to the model and pass it to view
 //note this done here only and i don't need to write it all over in every action
   ((MvcViewModelFilterAttribute.Models.CommonModel)model).SecurityClass = new Models.SecurityClass();
    ((MvcViewModelFilterAttribute.Models.CommonModel)model).SecurityClass.UserName = username;

First we cast our model object to “CommonModel” Class which is a class all models inherits and we assign data to this base class.

 public class CommonModel
    {
        public string ErrorMessage
        {
            get;
            set;
        }

        public SecurityClass SecurityClass
        {
            get;
            set;
        }
    }

The Model Calss

 public class AccountModel : CommonModel
    {
        public string UserName
        {
            get;
            set;
        }

        public string Email
        {
            get;
            set;
        }

        public string Password
        {
            get;
            set;
        }
    }

Conclusion
We can make base class that all models inherits and we can fill this base class with data

How to Use

 [MvcViewModelFilterAttribute.Filters.ViewModelFilter(Controller = "Account")]
    public class AccountController : Controller
    {
        //
        // GET: /Account/
   
        public ActionResult Index()
        {
            return View();
        }
     
        public ActionResult Create()
        {
            return View(SiteViewModels.AccountViewModels.Instance.GetAccountObject(null));
        }

        public ActionResult Edit(int? userID)
        {
           
            return View(SiteViewModels.AccountViewModels.Instance. EditAction(5));
        }
        public ActionResult Details(int? userID)
        {
            return View(SiteViewModels.AccountViewModels.Instance. EditAction(5));
        }
    }

We can see that we can pass any given parameters like “Controller” to get data with or action name.
Project on the run
run the project and type “localhost:{port}/account/create/” or “localhost:{port}/account/edit/”
ViewModelFilterAttribute2

ViewModelFilterAttribute3

You can download the complete project from This link MvcViewModelFilterAttribute