Click here to Skip to main content
15,879,239 members
Articles / Web Development / HTML
Tip/Trick

MVC Attributes

Rate me:
Please Sign up or sign in to vote.
4.90/5 (25 votes)
1 Oct 2015CPOL3 min read 44.4K   421   32   2
Some useful MVC Attributes (Bind Attribute, HandleError Attribute, HiddenInput Attribute, Remote Attribute)

Introduction

In the last blog post, I discussed SignalR and created a Message watch application through SignalR with database notification.

In my first article, I covered CRUD operation in MVC with MongoDB.

Today, I am going to cover some MVC attributes which can be very useful in development. I am going to cover the below 4 attributes:

  1. BindAttribute
  2. Remote
  3. Handle Error
  4. HiddenInput

Bind Attribute

The purpose of using BindAttribute is to restrict user to assign property values in Strong Typed Model while form posting. When we post a form, then each and every form property binds to the associated model property.

Suppose we have the below model:

C#
public class Employee
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public string PhoneNo { get; set; }
}

I have a controller named Employee which has the below two actions:

C#
 [HttpGet]
public ActionResult EmployeeRegister()
  {
    return View();
  }

 [HttpPost]
public ActionResult EmployeeRegister(Employee emp)
  {
    return View();
  }

From the first action, I create a view as below:

Image 1

If we run the app and fill the registration form as below:

Image 2

If we will post, then in second action method, we will get values as below:

Image 3

Now if we want to post only Email, Name and PhoneNo, and we don't want to send Address while posting, then we can do this with Bind attribute as below:

C#
[Bind(Exclude="Address")]
   public class Employee
   {
       public string Name { get; set; }
       public string Email { get; set; }
       public string Address { get; set; }
       public string PhoneNo { get; set; }
   }

Bind attribute is available in System.Web.Mvc namespace, so by using Bind attribute, we can add more control on values while posting a form. As per below screenshot, now we will not receive address while posting a form.

Image 4

In Bind Attribute, we can use the Include and Prefix property also apart from exclude.

We can use the Bind Attribute in Action method also as below:

Image 5

Remote Attribute

Suppose we have a registration form on which we have an email textbox and while entering email, we want to check whether that email already exists in database or not without posting the complete form. So in such a scenario, we can take the help of Remote Attribute. Through Remote Attribute, we can make a server call without posting the complete form.

We can apply Remote Attribute on that property which we want to check instantly like email in our case:

C#
public class Employee
{
    public string Name { get; set; }

    [Remote("CheckEmail","Employee",ErrorMessage="Email is already exist")]
    public string Email { get; set; }
    public string Address { get; set; }
    public string PhoneNo { get; set; }
}

First parameter is an Action Name, the second is Controller Name and the third one is error message which we want to display if email exists in database. It means whenever user will enter an email in email text box, CheckEmail ActionMethod will get called and check whether email exists or not.

C#
public JsonResult CheckEmail(string Email)
  {
      //Check here in database if it exist in database return true else false.
      return Json(false, JsonRequestBehavior.AllowGet);
  }

and here is the output:

Image 6

HandleError Attribute

There are many ways to handle an exception in MVC like normal try catch or through Filter or through third party libraries like elmah. But MVC also provides an attribute to handle exception which works as below:

C#
[HandleError()]
public ActionResult CheckError()
  {
     int a = 10;
     int b = 0;
     int k = a / b;
     return View();
  }

In web.config file, add the below lines:

XML
<customErrors mode ="On" defaultRedirect ="Error.cshtml">
</customErrors>

Create a view named Error.cshtml inside shared folder and run the application. If you will run and call this action method, your Error.cshtml will render in browser.

We can define different view in case of different type of exception in HandleError Attribute as below:

C#
[HandleError(ExceptionType=typeof(DivideByZeroException),View="DivideByZeroErrorView")]
[HandleError(ExceptionType = typeof(NullReferenceException), View = "NullRefrenceErrorView")]
public ActionResult CheckError()
       {
           int a = 10;
           int b = 0;
           int k = a / b;
           return View();
       }

HiddenInput Attribute

If we want to hide some model property from user, then we can take advantage of HiddenInput Attribute.

C#
public class Employee
    {
        [HiddenInput(DisplayValue=false)]
        public string Name { get; set; }

        [Remote("CheckEmail","Employee",ErrorMessage="Email is already exist")]
        public string Email { get; set; }

        public string Address { get; set; }

        public string PhoneNo { get; set; }
    }

In the above model, I decorate Name property with HiddenInput attribute. Now this Name property will not render in browser. So HiddenInput gives us extra control on Model Fields.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Hi Myself Vijay having around 7 years of experience on Microsoft Technologies.

Comments and Discussions

 
GeneralInformative tip Pin
Manas_Kumar2-Oct-15 2:48
professionalManas_Kumar2-Oct-15 2:48 
GeneralMy vote of 5 Pin
Carsten V2.01-Oct-15 20:33
Carsten V2.01-Oct-15 20:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.