最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How To access and display the data from database using ajax jquery asp.net mvc - Stack Overflow

programmeradmin3浏览0评论

I Am trying to fetch the data from database and display it in the page using ajax and jquery. Am new to this platform so can anyone help me Model:

 public class EmployeeModel
 {
    public int EmpId { get; set; }

    public string EmpName { get; set; }

    public int Age { get; set; }

    public int Salary { get; set; }

 }

Controller :

 private static readonly string connectionString =    ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString;
    public ActionResult GetUser()
    {
        return View();
    }

    public JsonResult GetAllUser(int EmpId)
    {
        List<EmployeeModel> employee = new List<EmployeeModel>();
        string query = string.Format("Select * From Employee", EmpId);
        SqlConnection connection = new SqlConnection(connectionString);
        {
            using (SqlCommand cmd = new SqlCommand(query, connection))
            {
                connection.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    employee.Add(
                        new EmployeeModel
                        {
                            EmpId = int.Parse(reader["EmpId"].ToString()),
                            EmpName = reader.GetValue(0).ToString(),
                            Age = int.Parse(reader["Age"].ToString()),
                            Salary = int.Parse(reader["Salary"].ToString())
                        }
                    );
                }
            }
            return Json(employee, JsonRequestBehavior.AllowGet);
        }
    }

ajax:

      @{
             ViewBag.Title = "Home Page";
             var EmployeeModel =                       (List<second_day.Models.EmployeeModel>)Model;
       }
     <div id="id"></div>
     <div id="firstName"></div>
<div id="lastName"></div>
<p id="getEmployee">Get Employee</p>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $('p#getEmployee').click(function () {
        GetEmployeeUsingAjax();
    });
});

 function GetEmployeeUsingAjax() {
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetAllUser")',
        data:{"EmpId":EmpId},
        dataType: 'json',
        success: function (data) {
            console.log(data);
            //$('#id').text(emp.employee.Id);
            //$('#firstName').text(emp.employee.FirstName);
            //$('#lastName').text(emp.employee.LastName);
        },
        error: function (emp) {
            alert('error');
        }
    });
}

Here i Need to fetch the data when its success else through error if it doesnt

Am new to this platform can anyone help me

I Am trying to fetch the data from database and display it in the page using ajax and jquery. Am new to this platform so can anyone help me Model:

 public class EmployeeModel
 {
    public int EmpId { get; set; }

    public string EmpName { get; set; }

    public int Age { get; set; }

    public int Salary { get; set; }

 }

Controller :

 private static readonly string connectionString =    ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString;
    public ActionResult GetUser()
    {
        return View();
    }

    public JsonResult GetAllUser(int EmpId)
    {
        List<EmployeeModel> employee = new List<EmployeeModel>();
        string query = string.Format("Select * From Employee", EmpId);
        SqlConnection connection = new SqlConnection(connectionString);
        {
            using (SqlCommand cmd = new SqlCommand(query, connection))
            {
                connection.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    employee.Add(
                        new EmployeeModel
                        {
                            EmpId = int.Parse(reader["EmpId"].ToString()),
                            EmpName = reader.GetValue(0).ToString(),
                            Age = int.Parse(reader["Age"].ToString()),
                            Salary = int.Parse(reader["Salary"].ToString())
                        }
                    );
                }
            }
            return Json(employee, JsonRequestBehavior.AllowGet);
        }
    }

ajax:

      @{
             ViewBag.Title = "Home Page";
             var EmployeeModel =                       (List<second_day.Models.EmployeeModel>)Model;
       }
     <div id="id"></div>
     <div id="firstName"></div>
<div id="lastName"></div>
<p id="getEmployee">Get Employee</p>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $('p#getEmployee').click(function () {
        GetEmployeeUsingAjax();
    });
});

 function GetEmployeeUsingAjax() {
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetAllUser")',
        data:{"EmpId":EmpId},
        dataType: 'json',
        success: function (data) {
            console.log(data);
            //$('#id').text(emp.employee.Id);
            //$('#firstName').text(emp.employee.FirstName);
            //$('#lastName').text(emp.employee.LastName);
        },
        error: function (emp) {
            alert('error');
        }
    });
}

Here i Need to fetch the data when its success else through error if it doesnt

Am new to this platform can anyone help me

Share Improve this question edited Dec 20, 2016 at 5:18 Sundar Stalin asked Dec 20, 2016 at 5:04 Sundar StalinSundar Stalin 992 gold badges2 silver badges9 bronze badges 10
  • you forgot the javascript man,i hope your editing the question right now – madalinivascu Commented Dec 20, 2016 at 5:06
  • Possible duplicate of How to render partial view in MVC5 via ajax call to a controller and return HTML – Muhammed Shevil KP Commented Dec 20, 2016 at 5:07
  • No @MuhammedShevilKP am not passing the view – Sundar Stalin Commented Dec 20, 2016 at 5:09
  • Add javascript code pls. – FakeisMe Commented Dec 20, 2016 at 5:11
  • @FakeisMe added it – Sundar Stalin Commented Dec 20, 2016 at 5:25
 |  Show 5 more ments

2 Answers 2

Reset to default 1
 function GetEmployeeUsingAjax() {
        var EmpId = 2;
        $.ajax({
            type: 'GET',
            url: '@Url.Action("GetAllUser")',
            data: { "EmpId": EmpId },
            dataType: 'json',
            success: function (data) {
                alert(data);
                //$('#id').text(emp.employee.Id);
                //$('#firstName').text(emp.employee.FirstName);
                //$('#lastName').text(emp.employee.LastName);
            },
            error: function (emp) {
                alert('error');
            }
        });
    }

       [HttpGet]
        public JsonResult GetAllUser(int EmpId)
        {
        // your code
       }

 plus string.Format("Select * From Employee where empid = {0} ",EmpId)

Please Check Below code :

var var EmpId = 2;
var abc = {
  "EmpId": EmpId 
};

 $.ajax(
{
url: '/ControllerName/GetAllUser/',
type: "GET",
async: false,
dataType: "json",
contentType: "application/json;",
data: JSON.stringify(abc),
success: function (result) {
alert(data);
}
});

And Action Should Be :

[HttpGet]
public JsonResult GetAllUser(int EmpId)
{

}

Happy !!

发布评论

评论列表(0)

  1. 暂无评论