Call Controller Action Method From jQuery Using Ajax in MVC

In this tutorial we have explain how to Call Controller Action Method From jQuery Using Ajax in MVC

Step 1 : first open visual studio and create web application and then create sql database with sql table

Step 2: then after create ado.net entity model as below image

Step 3: After creating controller you can add action method gettable()

 public ActionResult gettable()
{
return View();
}

public JsonResult GetUser()
{
List<tbl_user> D = new List<tbl_user>();
using (Database1Entities2 dc = new Database1Entities2())
{
D = dc.tbl_user.ToList();
}
return new JsonResult { Data = D, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Step 4 : Now add view as following

@model MvcApplication1.Database1Entities2

@{
ViewBag.Title = “gettable”;
}
<h2>gettable</h2>

@section Scripts{

<script>
$(document).ready(function () {
$(“#btnUser”).click(function () {
$.ajax({
url: ‘@Url.Action(“GetUser”,”ABC”)’,
data: “”,
type: “GET”,
dataType: “json”,
success: function (data) {
loadData(data);
},
error: function () {
alert(“error Please try again.”);
}
});
});
function loadData(data) {
var tab = $(‘<table style=Background-color:yellow></table>’);
var thead = $(‘<thead></thead>’);
thead.append(‘<th> ID</th>’);
thead.append(‘<th>Name</th>’);
thead.append(‘<th>City</th>’);
thead.append(‘<th>Education </th>’);
tab.append(thead);
$.each(data, function (i, val) {
var trow = $(‘<tr></tr>’);
trow.append(‘<td>’ + val.Id + ‘</td>’);
trow.append(‘<td>’ + val.Name + ‘</td>’);
trow.append(‘<td>’ + val.City + ‘</td>’);
trow.append(‘<td>’ + val.Education + ‘</td>’);
tab.append(trow);
});

$(“#DivId”).html(tab);
};
});
</script>
}
<table>
<tr>
<td>
<input type=”button” value=”Get User” id=”btnUser” />
</td>
</tr>
<tr>
<td>
<div id=”DivId”>
</div>
</td>
</tr>
</table>

Here we can call controller method using the ajax url and get response from the controller via the json respons and bind  data in html table. when you can click on the button the table data can be display as below o/p

SEE MORE

Leave a Reply

Your email address will not be published. Required fields are marked *