Friday 10 January 2014

Creating the Custom Action Filter Attribute

In this article we are going to see how to create a custom action filter attribute, For this we have to derive from the ActionFilterAttribute or its derived class. In this sample we are going to implement a Cache settings through the web.config and specify the cache profile name in the action filter to load for that particular action.


Filter :


    public class PartialCacheAttribute:OutputCacheAttribute
    {
        public PartialCacheAttribute(string cacheprofilename)
        {
            OutputCacheSettingsSection section = (OutputCacheSettingsSection)ConfigurationManager.GetSection("system.web/caching/outputCacheSettings");
            OutputCacheProfile profile =   section.OutputCacheProfiles["2Mcache"];
            Duration = profile.Duration;
            VaryByParam = profile.VaryByParam;
        }
    }
              

Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EFSample.Models;
using EFSample.Filters;

namespace EFSample.Controllers
{

    [Authorize]  
    [NoCache]
    public class EmployeeController : Controller
    {
        Models.EmpModel mod = new Models.EmpModel();

        public ActionResult Create()
        {
            return View();
        }

       
        public ActionResult Index()
        {
            List<EMPTABLE> result = mod.GetEmployees();
            return View(result);
        }

        [ChildActionOnly]
        [PartialCache("childprofile")]
        public ActionResult Child()
        {
            return View();
        }

       
        public ActionResult Details(int id)
        {
            EMPTABLE result = mod.GetEmployee(id);
            return View(result);
        }

    }
}



Web.Config

<system.web>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="2Mcache" duration="120" varyByParam="None"/>
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
</system.web>
   
Now from the code that the action child is cached to the system for 120 seconds, it takes the settings from the web.config.

From this article I hope you can learn how to implement the action filters in the ASP.NET MVC.

No comments:

Post a Comment