You can implement AJAX in two ways in MVC:
Below is a simple sample of how to implement AJAX by using the “AJAX” helper library. In the below code you can see we have a simple form which is created by using the Ajax.BeginForm
syntax. This form calls a controller action called getCustomer
. So now the submit action click will be an asynchronous AJAX call.
<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>
<div>
<%
var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %>
In case you want to make AJAX calls on hyperlink clicks, you can use the Ajax.ActionLink
function as shown in the below code.
So if you want to create an AJAX asynchronous hyperlink by name GetDate
which calls the GetDate
function in the controller, below is the code for that. Once the controller responds, this data is displayed in the HTML DIV
tag named DateDiv
.
<span id="DateDiv" />
<%:
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%>
Below is the controller code. You can see how the 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 an 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 into a function called GetData
and you can make a call to the GetData
function on a button or a hyperlink click event as you want.
function GetData()
{
var url = "/MyAjax/getCustomer";
$.post(url, function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
}
)
}