Quote for the Week

"Learn to enjoy every moment of your life"

Tuesday, September 2, 2014

How get JSON Data and set to the text boxes using Ajax call in jQuery in Asp.net MVC

Today, we will see how to get JSON data using Ajax in jQuery


I have table "tblEmployee" in SQL Server database like




and View design


<table>
<tr>
<td>Specify Employee Id:</td>
<td>
<input type="text" value="" id="txtEmpId"/>
</td>
<tr>
<td>First Name</td><td><input type="text" id="txtFirstName"></td>
</tr>
<tr>
<td>Annual Salary</td><td><input type="text" id="txtAnnualSal"></td>
</tr>
<tr>
<td>Country</td><td><input type="text" id="txtCountry"></td>
</tr>
<tr>
<td>Culture</td><td><input type="text" id="txtCulture"></td>
</tr>
</table>
<input type="button" value="Get Result" id="btnUpdate"/>


In your Controller Action Method


public JsonResult GetEmployeeDetails(int empid)
{

var employeeDetails=(from emp in context.TBLEMPLOYEE where emp.ID=empid
                               select  emp).FirstorDefault();

return Json(employeeDetails,JsonRequestBehaviour.AllowGet);
}

In your Script

<script>
$(document).ready(function(){
$("#btnUpdate").click(function(){
var empid=$("#txtEmpId").val();
$.ajax({
                url: '/your controller/GetEmployeeDetails',
               type: 'POST',
               data: empid,
              error: function () {
               alert(" An error occurred.");
                },
               success: function (data) {
              $("#txtFirstName").val(data[o].FirstName);
              $("#txtAnnualSal").val(data[o].AnnualSalary);
              $("#txtCountry").val(data[o].Country);
              $("#txtCulture").val(data[o].Culture);
              }
             });
 });
});
</script>


Summary:

Do you like this Article? then subscribe and follow this blog.

Have queries ? you can mail to dotnetcircle@gmail.com

No comments: