AJAX helper methods are like HTML helper methods , both are used for creating the HTML markup.The only difference between the two is that while HTML helper methods sends request to action methods synchronously,AJAX helper methods calls action methods asynchronously.Here we will understand basics of Ajax Helpers in ASP.NET MVC.
AJAX helper methods are defined as extension methods of the AJAXHelper class which exist in System.Web.Mvc.Ajax namespace.
For working with AJAX helper methods download the following NuGet Package:
Microsoft.jQuery.Unobtrusive.Ajax
AjaxOptions is a class used by most of the Ajax Helpers in ASP.NET MVC.
Ajax Options are settings of Ajax scripts.Some useful settings or options of AjaxOptions are:
- Confirm – for displaying confirmation box which has ok and cancel buttons.Clicking on ok button makes the Ajax request.
- InsertionMode – How the DOM should be updated with returned value.Valid values are:
- InsertAfter
- InsertBefore
- Replace
- LoadingElementId -Progess reporting element id.
- UpdateTargetId-Element id of the DOM element to update with returned data.
- URL-Action method to call
Common Ajax Helpers in ASP.NET MVC
One of the commonly used Ajax helper is ActionLink.It is used for asynchronously calling an action method when an action link is clicked.
You use ActionLink as:
@AJAX.ActionLink(("Link Text", "Action Method", new AjaxOptions {UpdateTargetId = "id", HttpMethod = "GET" })
AJAX.ActionLink has several overloads.Some of the arguments you can specify while calling this method:
- Controller name
- Action name
- LinkText
- Route values
- AjaxOptions
- hostName
- protocol
One overload of ActionLink method is defined as:
ActionLink method has the following signature
public static MvcHtmlString ActionLink( this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, AjaxOptions ajaxOptions )
first parameter is defined using this since this is an extension method and we are adding this extension method to AjaxHelper class.
AJAX.BeginForm
One useful AjaxHelper is BeginForm.This is used to create a form which can be posted asynchronously.Ajax.BeginForm requires some parameters to be passed such as Action name,Controller name,route values and options.
So you can declare AjaxOptions object and assign the properties of this object:
AjaxOptions options = new AjaxOptions(); options.HttpMethod = "GET"; options.OnBegin = "OnBeginRequest"; options.OnSuccess = "OnSuccess"; options.OnComplete = "OnComplete"; options.OnFailure = "OnFailure";
then you can pass this to the Ajax.BeginForm() method as:
@using (Ajax.BeginForm ("AjaxResult", "Home", options)) { }
in this example action method name is AjaxResult and Controller name is Home
Some other useful extension methods of AjaxHelper class are:
- RouteLink
- GlobalizationScript
- BeginRouteForm
Leave a Reply