Implement Ajax in MVC
You can implement Ajax in two ways in MVC:-
- Ajax libraries
- Jquery
Below is a simple sample of how to implement Ajax by using “Ajax” helper library. In the below code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This form calls a controller action called as “getCustomer”. So now the submit action click will be an asynchronous ajax call.
<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>
<%
var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" />
<input id="txtCustomerName" type="text" />
<input id="Submit2" type="submit" value="submit"/><%} %>
In case you want to make ajax calls on hyperlink clicks you can use “Ajax.ActionLink” function as shown in the below code.
So if you want to create Ajax asynchronous hyperlink by name “GetDate” which calls the “GetDate” function on the controller , below is the code for the same. Once the controller responds this data is displayed in the HTML DIV tag by name “DateDiv”.
<span id="DateDiv" />
<%:
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%>
Below is the controller code. You can see how “GetDate” function has a pause of 10 seconds.
public class Default1Controller : Controller
{
public string GetDate()
{
Thread.Sleep(10000);
return DateTime.Now.ToString();
}
}
The second way of making Ajax call in MVC is by using Jquery. In the below code you can see we are making an ajax POST call to a URL “/MyAjax/getCustomer”. This is done by using “$.post”. All this logic is put in to a function called as “GetData” and you can make a call to the “GetData” function on a button or a hyper link click event as you want.
function GetData()
{
var url = "/MyAjax/getCustomer";
$.post(url, function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
}
)
}
What kind of events can be tracked in AJAX ?

