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?
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.
my 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
[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 >
<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" id="IDbtn" onclick="GetByName($('#drpList').val())">Get Data By Name</Button>
@*Data Table ==============*@
<table 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 >UpdateEmp</asp:button> |
<asp:button 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
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 >UpdateEmp</asp:button> | <asp:button 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
How can I send data from my controller to my DataTable using Ajax?
CodePudding user response:
It's because you return your data with employeeId, name
properties but you try to append with EmployeeId, Name
. You need to be careful with casing of your object.
rows = `<tr>
<td style="Display:none">${item.employeeId}</td>
<td>${item.name}</td>
<td>${item.gender}</td> ...