简体   繁体   English

Ajax & ASP.NET MVC:在不使用实体框架的情况下通过 ID 获取数据

[英]Ajax & ASP.NET MVC : get data by ID without using Entity Framework

I am trying to get data in my DataTable by ID, the data row coming from SQL Server to my controller but I am confused: how to pass this data to my DataTable in view?我正在尝试按 ID 在我的 DataTable 中获取数据,数据行来自 SQL 服务器到我的 controller 但我很困惑:如何将这些数据传递给我的 DataTable 视图?

I am using this code - my model:我正在使用这个代码 - 我的 model:

public class EmployeesModel
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public int Age { get; set; }
    public string Position { get; set; }
    public string Office { get; set; }
    [Required(ErrorMessage ="Please enter date")]
    public DateTime HiringDate { get; set; }
    public int Salary { get; set; }
}

My controller我的 controller

    public JsonResult GetEmpByID(int id)
    {

        List<EmployeesModel> employeeList = new List<EmployeesModel>();
        string CS = ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString;

        using (SqlConnection conn = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("SP_GetEmpByID", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@EmpID", SqlDbType.NVarChar).Value = id; //Added Parameter

            conn.Open();

            // Get
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                EmployeesModel employee = new EmployeesModel();

                employee.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);
                employee.Name = reader["Name"].ToString();
                employee.Gender = reader["Gender"].ToString();
                employee.Age = Convert.ToInt32(reader["Age"]);
                employee.Position = reader["Position"].ToString();
                employee.Office = reader["Office"].ToString();
                employee.HiringDate = Convert.ToDateTime(reader["HiringDate"]);
                employee.Salary = Convert.ToInt32(reader["Salary"]);

                employeeList.Add(employee);
            }
        }

        //return View(employeeList); Commented out
        //return RedirectToAction("GetEmpByID"); Commented out
        return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
    }

My view我的观点

@model IEnumerable<SQLWithoutEF.EmployeesModel>

<input type="text" id="tablename" />  //Here I enter Employee ID and below is button
<asp:Button runat="server" Text="Button" class="btn btn-danger" id="IDbtn" onclick="GetByName($('#tablename').val())">Get Data By ID</asp:Button>

@*Data Table ==============*@
<table class="table table-bordered table-responsive table-hover" id="MyTable">
    <thead>
        <tr>
            <th style="display:none">@Html.DisplayNameFor(m => m.EmployeeId)</th>
            <th>@Html.DisplayNameFor(m => m.Name)</th>
            <th>@Html.DisplayNameFor(m => m.Gender)</th>
            <th>@Html.DisplayNameFor(m => m.Age)</th>
            <th>@Html.DisplayNameFor(m => m.Position)</th>
            <th>@Html.DisplayNameFor(m => m.Office)</th>
            <th>@Html.DisplayNameFor(m => m.HiringDate)</th>
            <th>@Html.DisplayNameFor(m => m.Salary)</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var employee1 in Model)
        {
            <tr>
                <td style="display:none">@employee1.EmployeeId</td>
                <td>@employee1.Name</td>
                <td>@employee1.Gender</td>
                <td>@employee1.Age</td>
                <td>@employee1.Position</td>
                <td>@employee1.Office</td>
                <td>
                    @if (employee1.HiringDate != null)
                    {
                        @employee1.HiringDate
                    }
                </td>
                <td>@employee1.Salary</td>
                <td>
                    <asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> |
                    <asp:button class="btn btn-danger btn-xs" data-name="@employee1.Name" id="deletebtn" onclick="deleteF(@employee1.EmployeeId)">DeleteEmp</asp:button>
                </td>
            </tr>
        }
    </tbody>
</table>

My jQuery / Ajax - here I need help:我的 jQuery / Ajax - 我需要帮助:

function GetByName(id) {
    if (confirm("Are You Sure to Get " + id + " " + " ?")) {
        $('#MyTable tbody tr').remove();
        $.ajax({
            type: "GET",
            url: '/Home/GetEmpByID?id=' + id,
            //data: JSON.stringify({ id: id }),
            //contentType: application/json, charset: utf-8,
            processData: false,
            dataType: 'json',
            bprocessing: true,
            success: function (data) {   // Till here data coming but it's not working further

                var items = '';
                $.each(data, function (item) {
                    debugger;
                    var rows = '';
                    for (var i = 0; i < item.length[0]; i++) {
                        rows = "<tr><td>" + data + "</td>"
                            + '<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="@employee1.Name" id="deletebtn" onclick="deleteF(@employee1.EmployeeId)">DeleteEmp</asp:button></td>'
                        "</tr>";
                        $('#MyTable tbody').append(rows);
                    }
                })
            },
        }).catch(function (xhr, status, error) {
            var errorMeassage = xhr.status + ': ' + xhr.statusText;
            alert('Error - ' + errorMeassage);
        })
    };
};

Here is the screenshot what output I am getting这是我得到的 output 的截图

enter image description here在此处输入图像描述

Kindly suggest how I can send data from my controller to my DataTable using Ajax?请建议我如何使用 Ajax 将数据从我的 controller 发送到我的 DataTable?

Thanks谢谢

From the controller API action,从 controller API 动作,

return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);

It will return the response with body as an object with data property which contains the array, instead of the response is the array.它将返回带有正文的响应作为 object 具有包含数组的data属性,而不是响应是数组。

The response body would be as:响应正文如下:

{
  data: [/* Employee List */]
}

In JavaScript part, to take the employee array在 JavaScript 部分,取员工数组

var items = data.data;

The implementation in success callback should be: success回调中的实现应该是:

var items = data.data;
$.each(items, function (index, item) {
    debugger;
    var rows = '';

    rows = `<tr>
        <td style="display:none">${item.EmployeeId}</td>
        <td>${item.Name}</td>
        <td>${item.Gender}</td>
        <td>${item.Age}</td>
        <td>${item.Position}</td>
        <td>${item.Office}</td>
        <td>${item.HiringDate}
        </td>
        <td>${item.Salary}</td>
        <td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="${item.Name}" id="deletebtn" onclick="deleteF(${item.EmployeeId}">DeleteEmp</asp:button></td>
    </tr>`;
    $('#MyTable tbody').append(rows);
})

Note: You may use the string interpolation / template literal which makes it easier to build the template string.注意:您可以使用字符串插值/ 模板文字,这样可以更轻松地构建模板字符串。

Demo演示

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM