简体   繁体   English

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

[英]Ajax & ASP.NET Core MVC 6..0 : 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 and passing to Jquery-Ajax but After processing in Ajax, I am getting only UNDEFINED in my DataTable View?我正在尝试按 ID 在我的 DataTable 中获取数据,数据行来自 SQL 服务器到我的 controller 并传递给 Jquery-Ajax 但在 Z3EB7106C3477A60E6 BBF5DBFDEFINEDAM59

Please note: I have used below code successfully in my ASP.Net MVC app but now after upgrading to ASP.NET CORE MVC 6.0 , It is giving only UNDEFINED.请注意:我已经在我的 ASP.Net MVC 应用程序中成功使用了以下代码,但现在在升级到ASP.NET CORE MVC 6.0之后,它只给出了 UNDEFINED。

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

        [HttpGet]
        public JsonResult GetEmpByName(string Name)
        {

            List<EmployeesModel> employeeList = new List<EmployeesModel>();
            string CS = this.Configuration.GetConnectionString("SQLConn");
            using (SqlConnection conn = new SqlConnection(CS))
            {
                SqlCommand cmd = new SqlCommand("SP_GetEmpByName", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@EmpName", SqlDbType.NVarChar).Value = Name; //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 Json(new { data = employeeList.ToList(), success = true, responsetext = "Added" });
        }

My view我的观点

@model IEnumerable<SQLWithoutEF.EmployeesModel>

<div class="form-control">
    <select class="form-select" id="drpList" onchange="getSelectedValue()">
        <option selected disabled>Please Select</option>
        @foreach(var employee in ViewBag.Employees)
        {
        <option value="@employee.EmployeeId">@employee.Name</option>
        }

    </select>
</div>
  //Here I enter Employee Name and below is button
  
<Button runat="server" Text="Button" class="btn btn-danger" id="IDbtn" onclick="GetByName($('#drpList').val())">Get Data By Name</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>@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: I have tried 3 methods but all fail我的 jQuery / Ajax - 在这里我需要帮助:我尝试了 3 种方法,但都失败了

 function GetByName(Name) { $('#MyTable tbody tr').remove(); $.ajax({ type: "GET", url: '/Home/GetEmpByName?Name=' + Name, //data: JSON.stringify({ id: id }), commented out //contentType: application/json, charset: utf - 8, commented out //cache: false, commented out processData: false, dataType: 'json', bprocessing: true, success: function (data) { var items = [data.data[0]]; //This line may be wrong, I am not sure. debugger; 3rd try -Failed //let rows = data.map(i=> "<tr><td>" + i.Name + "</td></tr>"); 2nd try -failed // for (var i = 1; i < items.length-1; i++) { // var rows = $('<tr> <td style="Display:none">' + items[EmployeeID] + '</td><td>' + items.data[i].Name + '</td><td>' + items[i][2] + '</td><td>' + items[i][3] + '</td><td>' + items[i][4] + '</td><td>' + items[i][5] + '</td><td>' + items[i][6] + '</td><td>' + items[i][7] + '</td><td>' + items[i][8] + '</td></tr>'); // $('#MyTable tbody').append(rows); // }; // 1st try failed $.each(items, function (index, item) { 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>${2020-04-04}</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); }); }, complete: function () { // setTimeout(function () { // $('.ajaxLoader').hide(); // }, 300); } }).catch(function (xhr, status, error) { var errorMeassage = xhr.status + ': ' + xhr.statusText; alert('Error - ' + errorMeassage); }) }; };

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

输出图像,请检查

输出图像 2

How can I send data from my controller to my DataTable using Ajax?如何使用 Ajax 从我的 controller 将数据发送到我的 DataTable?

It's because you return your data with employeeId, name properties but you try to append with EmployeeId, Name .这是因为您使用employeeId, name属性返回数据,但您尝试使用EmployeeId, Name来 append 。 You need to be careful with casing of your object.您需要小心 object 的外壳。

rows = `<tr>
<td style="Display:none">${item.employeeId}</td>
<td>${item.name}</td>
<td>${item.gender}</td> ...

暂无
暂无

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

相关问题 Ajax &amp; ASP.NET MVC:在不使用实体框架的情况下通过 ID 获取数据 - Ajax & ASP.NET MVC : get data by ID without using Entity Framework 在没有实体框架和迁移的ASP.NET Core MVC应用程序中使用ASP.NET标识 - Using ASP.NET Identity in an ASP.NET Core MVC application without Entity Framework and Migrations ASP.NET Core MVC + Entity Framework Core 如何获取新添加的 object 的 id - How ASP.NET Core MVC + Entity Framework Core get the id of a newly added object ASP.NET Core MVC +实体框架+ GET +数组 - ASP.NET Core MVC + Entity Framework + GET + Array ASP.NET Core MVC &amp; C#:使用实体框架将数据插入数据库 - ASP.NET Core MVC & C# : insert data into database using Entity Framework ASP.NET Core 2.2实体框架:在不更改上下文的情况下获取数据子集 - ASP.NET Core 2.2 Entity Framework: Get subset of data without altering context 在ASP.NET MVC中使用实体框架进行数据访问 - Data access using Entity Framework in ASP.NET MVC Entity Framework Core 和 ASP.NET Core MVC 中的 Inheritance 数据库 - Inheritance Database in Entity Framework Core and ASP.NET Core MVC 如何使用 Ajax 在 Asp.net 核心 MVC 中刷新数据而不重新加载页面? - How to refresh data without page reloading in Asp.net core MVC using Ajax? 如何在 ubuntu 桌面上使用 Entity Framework Core 将 asp.net core MVC 项目连接到本地数据库 - how to connect asp.net core MVC project to local DB using Entity Framework Core on ubuntu desktop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM