Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Thursday, 20 December 2012

Custom or User define Attribute in MVC


Hello frnd ,
I am writing this blog for a type of problem which we face during development in mvc-3 or mvc4 .
For a registered user we have to check Session  in every action of every controller ,which is very tedious.
Like this ,
                If (YourSessionObject != null)
{
                //your code goes here.
}

It is very tedious.
So Here is the solution.
You all know about Mvc Attributes. So we can make one attribute which will check our session object and if found null then return back to login page.
So the question is where to write this class, The class will be written in App_Start .
The class should implement ActionFilterAttribute.

In that class you have to over ride OnActionExecuting method.
Here is the code below

public class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            CurrentCustomer objCurrentCustomer = new CurrentCustomer(); //This is session object
            objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
            if (objCurrentCustomer == null)
            {
                // check if a new session id was generated
                filterContext.Result = new RedirectResult("~/Users/Login"); // if null then return back to login page .
                return;
            }

            base.OnActionExecuting(filterContext);
        }
    }
That’s all just include App_Start in controller and just add [SessionExpireFilter] attribute in your action method.
This will check session in every action .

Partial View Rendering methods

I've noticed there are several ways to use Views and PartialViews:

RenderAction, RenderPartial, and "return PartialView"

RenderAction when placed inside HTML, will simply call an Action and Render the View returned (the View returned can be partial view or view?)

RenderPartial will simply retrieve the contents of a View without executing any Controller action.

return View() returns the view with a Layout enabled so you get full HTML page with <html> and <body> tags. return PartialView() on the other hand disables the Layout and you get only the HTML fragment contained in this view.


Thanks
V. K. Rajput
Fokat RnD Team member