Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Ajax

Unobstrusive Ajax and Handle Unauthorized Request in MVC

5.00/5 (3 votes)
5 Apr 2016CPOL4 min read 14.5K  
Unobstrusive Ajax and how to handle unauthorized request in MVC

Introduction

In this article, I will be sharing some basic stuff which comes in handy in MVC applications. The HTML helpers provided by the Razor are smart enough to understand and process the work as required.
We will be discussing in brief about the Ajax.BeginForm, which has few concepts hidden within. When we face the difficulty or the issue, we explore and resolve. Same has happened recently with me. So let's start exploring what the hidden secrets are, which actually are very few.

Adding Unobstrusive- Ajax JS

This can be added from the Nuget package manager directly. I find adding from the Package Manager console easy. The script goes like below:

Install-Package jQuery.Ajax.Unobtrusive

Snippet & Learning

AjaxExtensions.BeginForm is a part of System.Web.Mvc.Ajax namespace under the System.Web.MVC assembly. When used in the response, it writes the HTML
<form> tag. Ajax, as we know is Asynchronous JavaScript and XML, the word asynchronous plays the trick actually. That means the call will be done asynchronously in some other thread, without hampering or halting the current executing thread for better user experience and performance. Thus, the Ajax call we used to write through jQuery, can be done by the MVC HTML helpers now.

One important point to remember here is we need to have the unobstrusive-ajax.js file in order for the Ajax.BeginForm to work in the actual manner.

The Ajax.BeginForm has three options attached to it.

JavaScript
@using (Ajax.BeginForm("ACTION", "CONTROLLER", 
	new AjaxOptions { UpdateTargetId = "TARGETID" ,OnSuccess="PostSuccess"}))
{
   <div id="TARGETID"></div>
   // Do anything you would like to.
}

Let's understand the properties it possesses.

The first param to the Ajax.BeginForm is Action Method, the action to which we will be posting or getting the results.

The second param is Controller, the route controller in which the Action Method is specified. The route table in turn configures accordingly.

The third is the important property of the Ajax.BeginForm as it gives us the different options in order to track and show the response, even manipulate the response.

  • UpdateTargetId: This property is used to track the ‘id’ where the Ajax response will be displayed.
  • OnSuccess, OnFailure, OnComplete, OnBegin: The second part of the option is the track functions. We can use the functions to track the event and update the UI accordingly. The methods are self explanatory so, I am not being stupid to explain the same. ??
  • HttpMethod: This again is self explanatory, it allows the POST GET to be specified explicitly.
  • AllowCache: This method in Ajax allows to either cache the response or not. By default, it caches the identical request’s response. So to avoid any kind of caching, we can use the Attribute [OutputCache(NoStore = true, Duration = 0, VaryByParam = “*”)]

These were few of the important properties discussed, which are frequently used.

Now another issue we face is when we have a session ended for any user, but the user is still on the web page, then we find that the login page loads in the partial part of the page only, not the whole page is reloaded to the Login page, which is really weird from any user point of view. This can easily be done and accomplished by changing the UpdateTargetId to the body or supplying any id to the body tag.

But sometimes, we have to handle the unauthorized access from the user during any Ajax calls. So, in case (everytime now in MVC projects, Authorize attribute and its virtual methods are overridden), inside the Custom Authorize attribute, we modify/override the HandleUnauthorizedRequest and handle the Ajax calls that are unauthorized. The code goes as below:

JavaScript
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { redirectTo = FormsAuthentication.LoginUrl }
                };
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }

filterContext.HttpContext.Request.IsAjaxRequest() is doing the trick here, tracking whether the request coming from the client is Ajax request or the normal request.

redirectTo = FormsAuthentication.LoginUrl -  This takes the default login URL from the app settings in Web.config file. Thus now the result of the context will be present in the current context and can be tracked by the Onsuccess method. The code can be seen below:

JavaScript
function PostSuccess(result) {
    if (result.redirectTo) {
        window.location.href = result.redirectTo;
    }
}

This is a simple part, we can also do the same tracking the reference of the result context and manipulate.

Conclusion

I tried to cover some basic stuff in the MVC application, which we use frequently in our application, we sometimes scratch our head to get a proper understanding and solution to a simple problem. I hope this has helped in some way. Any suggestions or more interesting facts are more than welcome.

Keep learning and keep sharing.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)