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

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^