Click here to Skip to main content
13,259,539 members (53,581 online)
Click here to Skip to main content
Add your own
alternative version

Stats

13.7K views
274 downloads
31 bookmarked
Posted 1 Oct 2015

MVC Attributes

, 1 Oct 2015
Rate this:
Please Sign up or sign in to vote.
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:

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:

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

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

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

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

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

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:

[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.

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:

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:

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.

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:

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:

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

In web.config file, add the below lines:

<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:

[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.

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)

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
GeneralInformative tip Pin
Manas_Kumar2-Oct-15 3:48
professionalManas_Kumar2-Oct-15 3:48 
GeneralMy vote of 5 Pin
Carsten V2.01-Oct-15 21:33
memberCarsten V2.01-Oct-15 21: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 1 Oct 2015
Article Copyright 2015 by VijayRana
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid