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.
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.
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:
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.