Monday, 20 February 2012

How to get the current controller and action names in View Mvc3

In MVC we can use the partial views to avoid the redundant code. I have one requirement that the action names are same in two different controllers and there is partial view which has one link which needs to point to the current controller with the same action. I want to access the controller name in View to avoid the redundant code. The solution to get the Controller and Action names in View as follows. Solution:
 @{
        var controller = this.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
    
        Change password
        }
If you want to access the action name
var action=this.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();

Jquery Ajax Request and Unauthorized Access handling in MVC3

When we are posting the data through jquery $.ajax and  we are using asp.net forms authentication, if the user is not authorized then we will redirect to the login page. the same login page response is return result as on jquery ajax success. If we throw any exception in controller or any custom authorize attribute then ajax request returns the 500 status code internal server exception as its default behaviour. 500 status code reruns any exception in the request processing. But our view is to return the 401 as the status code. I research about many hours to get this solution.

Solution1:

1. Custom authentication attribute
public class AdminAuthorizeAttribute : AuthorizeAttribute  
{   
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {    
  User currentUser = ClientContext.Current.User;    

  return currentUser != null;      

 }

}
If the user is not authenticated the reruns to logon action as i am using forms authentication in asp.net.
2. In the controller action result write the following
 public ActionResult Logon()
 {
  if (Request.IsAjaxRequest())
  {
 
  //this is used when the authentication fails in the ajax request
  //this returns the httpstatus code 401 to the browser.
 
   ControllerContext.HttpContext.Response.StatusCode = 401;
 
   return Content(string.Empty);
  
   }

 } 
3. Handle the status codes in jquery $.ajaxSetup
$.ajaxSetup({
             statusCode: {
                        401: function () {
 
                            // Redirect the to the login page.
                            window.location = "/login/";
 
                        }
                    }
            });
Solution2:
public class AdminAuthorizeAttribute : AuthorizeAttribute  
{   
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {    
  User currentUser = ClientContext.Current.User;    

  return currentUser != null;      

 }


public override void OnAuthorization(AuthorizationContext filterContext)
{
   base.OnAuthorization(filterContext);

  // If its an unauthorized/timed out ajax request go to top window and redirect to logon.
    if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest())
    {
filterContext.Result = new JavaScriptResult() { Script = "top.location.reload()"    };
    }

  // If authorization results in HttpUnauthorizedResult, redirect to error page instead of Logon page.
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                if (ClientContext.Current.User == null)
                {
                    filterContext.Result =
                        new RedirectResult(
                            string.Format(
                                "~/logon/logon?ReturnUrl={0}",
                                HttpUtility.HtmlEncode(filterContext.HttpContext.Request.RawUrl)));
                }
                else
                {
                    filterContext.Result =
                       new RedirectResult(string.Format("~/error/unauthorized"));
                }
            }
        }
}
I hope this will help you.