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:
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.
- @using (Ajax.BeginForm("ACTION", "CONTROLLER", new AjaxOptions { UpdateTargetId = "TARGETID" ,OnSuccess="PostSuccess"}))
- {
- <div id="TARGETID"></div>
- // Do anything you would like to.
- }
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);
- }
- }
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;
- }
- }
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.

Ajay MalikPosted Jun 1, 2016, 11:22 AM
Nice...
Jaipal ReddyPosted Apr 5, 2016, 11:56 PM
Nice one. .
Gowtham KPosted Apr 5, 2016, 1:15 PM
Great Work, Thanks for sharing
Mohammed IbrahimPosted Apr 5, 2016, 12:26 PM
nice
Debasis SahaPosted Apr 5, 2016, 10:22 AM
Nice One..
Ankur MistryPosted Apr 5, 2016, 10:10 AM
Nice Share
Rahul Kumar SaxenaPosted Apr 5, 2016, 8:53 AM
Quality Words..
Vignesh ManiPosted Apr 5, 2016, 8:20 AM
Nice