I’m reading some examples and i keep seeing code with [SOMETHING] before methods and I’d like to know what that’s called and how it’s used.
Can you define you own [SOMETHING] or is there a defined list of these things?
Here’s some code examples I found that use this thing but don’t explain anything about it.
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
Sometimes they even put parameters in it too like
[HandleError(Order = 2)]
Whats going on here. I feel like this is SUPER important but none of the reference books I’ve read explain it they just use them.
Thanks ahead of time.
HandleErroris an attribute.Brief Intro to Attributes
Attributes are contained in square brackets, prefixing classes, structs, fields, parameters, functions, and arguments, and you can define your own by inheriting from Attribute in a class. The typical format of creating an attribute is as such:
You can also prefix your attribute definition with an attribute that defines the scope of what it can apply to:
In the example above, there really isn’t that much to the class, other than it just being a decorator for a class or a struct. Consider an example from the MSDN, where classes can be given an Author attribute (http://msdn.microsoft.com/en-us/library/z919e8tw%28v=vs.80%29.aspx):
In the case of HandleError, specifically:
They provide helpful information that can be seen via reflection. In the case of
HandleError, it means that if any exception is thrown within the controller, that it will render the Error view in ~/Views/Shared/.See http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute.aspx for more details.