create attribute in mvc 5

How to create Attribute in MVC 5

Hello everyone, I'm going to share the steps for how to create attributes in mvc applications which are given below in details.

Table of Contents

Step 1. First create a class and inherit the FilterAttribute class or Attribute.
Step 2. Add the class name as attribute on tap on controller as well as actions method. 

In the below example you can seen the IsValidUser is class name as well as attribute name on controller or action methods.


Step1 : Here IsValidUser is a model class which inherited to filter attribute and its work like attribute.


namespace WebApplication1.Models
{
    public class IsValidUser : FilterAttribute
    {
        // here declaring constructor without parameter.
        public IsValidUser()
        {           
        }
    }

}


Step2 : This is controller class and here IsValidUser class use like attribute on top of the account controller or login action mrthod.

namespace WebApplication1.Controllers
{
    [IsValidUser]
    public class AccountController : Controller
    {    
        [IsValidUser]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
    }
}


ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.