Filter in Mvc
You have learned how to use viewbag ,viewdata and tempdata the previous section. Here, you will learn what is filter in mvc and how will i use it inside application.
Filters is most important concepts in mvc,Filter is a special type trigger , An action filter is an attribute that you can apply to a action method or whole controller , it execute before or after on action method calling. its depend on user logic.mvc filter is a custom class. inwhich you can write user define logics to execure before and after action method.
Filter can be applied on action method or controller level or global lebel also.
Mvc Provide different types of filter such as
- Authorization filters
- Action filters
- Result filters
- Exception filters
MVC Filters are used to perform some common functionalities in application.
- Authorization and Authentication (in mvc5)
- Caching
- Logging
- ValidateInput
- RequireHttps
- Error Handling , etc.
Action filter are also use different types
OutputCacheWe need caching in many different ,if we want to improve webpage loding ,or we do not want every time it request to server for same page so here we can use caching. it main feature is speed up the web page,server load reduce .here you can define caching time on action method,controller level or globally.
[OutputCache(Duration = 160)] public ActionResult home(){ var student = from e in db.students orderby e.ID select e; return View(student); }
Cache Profile
HandleError
This action filter handles errors raised when a controller action executes.
AuthorizeThis action filter enables you to restrict access to a particular user or role.
How will Add the filters in ASP.NET MVC?you can add three different levels of our application. They are as follows
- Action Level
- Controller Level
- Global Level
public class EmployeeController : Controller
{
[Authorize(Users = "admin,User2")]
public ActionResult Showdetail(string id)
{
// You logic
return View();
}
}
[Authorize(Roles = "Administrator")]
public class AdministratorController : Controller
{
//You logic
}
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
Learn how to set image path in StyleBundle.
- Use Styles.Render("bundle name") method to include style bundles in a razor view.