Using AJAX in MVC

ASP.NET AJAX enables a Web application to retrieve data from the server asynchronously and to update parts of the existing page. This results in improved user experience by making the Web application more responsive. More detail to add Ajax scripting to MVC project can be found here.

In MVC, Ajax helper can be used in same way we use in traditional ASP.NET to create AJAX enabled elements/Forms/links which performs request asynchronously. AJAX Helpers are extension methods of AJAX Helper class which exist in System.Web.Mvc namespace.


1.    Using Ajax.ActionLink

Returns an anchor element that contains the URL to the specified action method; when the action link is clicked, the action method is invoked asynchronously by using JavaScript. 
For using Ajax action link there are various overloaded methods are available, one of them is as below,

public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes);

Can be used as,

@Ajax.ActionLink("linkText""ActionName","ControllerName"new { Route = ”Value” }, new AjaxOptions { UpdateTargetId = "divSectionID", OnFailure = "AjaxFailure", OnBegin = "AjaxBegin", OnComplete = "AjaxComplete", InsertionMode= InsertionMode.Replace }, new { @class = "btn-primary btn-sm" }) 

For details of overloaded methods use below link,

ActionLink placed in view can update the page section with ID as specified in AjaxOptions “UpdateTargetId”, Link will be created with Action and controller name as defined. Value to route can be passed as shown, AjaxOptions (explained at end) are defined, and HTML attribute to link/element can be given/applied at the end.


2.    Using Ajax.BeginForm

Writes an opening <form> tag to the response. With the use of Ajax.BeginForm we can post back particular section of page to server and get result back. Most of the time it can be used with partial view where we need only some part of view or complete partial view to post back to server and get result. In such case we can have multiple submit buttons on page which will submit only particular section of page to server.   

Similar to Ajax.Actionlink there are various overloads are available below example is one of them,

public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes);

Can be used on view as,

@using (Ajax.BeginForm("actionName ""controllerName"new { Value = “RouteValue” }, new AjaxOptions { UpdateTargetId = "HTMLElemntIDtoUpdate", HttpMethod = "POST" }))
{
<div id="HTMLElemntIDtoUpdate">
/////Your HTML/Razor code////
</div>
}

For details of overloaded methods use below link,

NOTE: - When we use Ajax.BeginForm, we did not need to do anything extra in terms of coding, like normal MVC action method our method will return view/actionresult and it will be placed at given location as coded.



AjaxOptions in Detail:-

The Ajax helper allow to configure several aspects of the Ajax request such as on success, failure or on request complete executing some JavaScript. Below are some properties can be used,


Property
Description
OnBegin
The OnBegin property specifies a name of JavaScript function that is called at the beginning of the Ajax request.
OnComplete
The OnComplete property specifies a name of JavaScript function that is called at the end of the Ajax request.
OnSuccess
The OnSuccess property specifies a name of JavaScript function that is called when the Ajax request is successful.
OnFailure
The OnFailure property specifies a name of JavaScript function that is called if the Ajax request fails.
UpdateTargetId
The UpdateTargetId property specifies an ID of a DOM element that will be populated with the HTML returned by the action method.
InsertionMode
The possible values are InsertAfter, InsertBefore and Replace to specify How updation will take place.
Url
URL to which the form is to be submitted. You can also specify a controller and action method in the BeginForm() method instead of setting the URL property.
HttpMethod
The HttpMethod property indicates the HTTP method (GET or POST) to be used
Confirm
The Confirm property is used to specify a message that will be displayed in a confirm dialog to the end user for request


3.    Ajax Method with jQuery:- 

We also have option call controller action method with jQuery, this can be usefule when you need some values to be set or update on some event. Below code shows same,

//Ajax call to get Details from contoller
        $.ajax({
            type: 'POST',//Action Type:- GET/POST
            url: '@Url.Action("ActionName", "ControllerName")',
            dataType: 'json',
            async: false,//Set False when you don't want call to be async, Defaut:- True
            data: { SelectedID: checkedIds.join(","), OtherID: 1 },//Data can be passed to controller method by name
            success: function (data) {
             //If Call is success, then we can access returned data here.  
            },
            error: function (ex) {
                //Somthing went wrong.
            }

        });


Comments