Introduction
In this article I will be sharing basic stuff which comes in handy in MVC applications. The HTML helpers provided by Razor are smart enough to understand and process the work as required.
We will be discussing in brief about the Ajax.BeginForm, which has a few concepts hidden within. When we face a difficulty or issue, we explore and resolve. The 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 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.
- @using (Ajax.BeginForm("ACTION", "CONTROLLER", new AjaxOptions { UpdateTargetId = "TARGETID" ,OnSuccess="PostSuccess"}))
- {
- <div id="TARGETID"></div>
-
- }
Lets 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 as well.
- 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 the functions to track the event and update the UI accordingly. The methods are self explanatory.
- 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 a 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, rather than the whole page is reloaded to the Login page, which is really weird from any users 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 (every time 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 like below:
- 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:
- 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 basic stuff in the MVC application which we use frequently in our application, and 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.
Read more articles on AJAX: