我正在尝试使用弹出窗口和 jQuery 进行增删改查操作,但一开始我只尝试使用 jQuery Ajax 在表中显示数据库中的数据。它不显示错误消息,但不从数据库获取数据。我在表视图中未定义数据。
这是
site.js
文件
$(document).ready(function () {
GetTeams();
});
function GetTeams() {
$.ajax(
{
url: '/Team/GetTeams',
type: 'Get',
datatype: 'json',
success: function (response) {
if (response == null || response == undefined || response.length ==0) {
var object = '';
object += '<tr>';
object += '<td class="colspan=5"> ' + 'No Team Exists' + '</td>';
object += '</td>';
object += '</tr>';
$('#tblBody').html(object);
}
else {
var object = '';
$.each(response, function (Index, item) {
object += '<tr>';
object += '<td > ' + item.TeamId + '</td>';
object += '<td > ' + item.TeamName + '</td>';
object += '<td > ' + item.Owner + '</td>';
object += '<td > ' + item.couchName + '</td>';
object += '</td>';
object += '</tr>';
});
$('#tblBody').html(object);
}
},
error: function () {
alert('Unable to Read Team Data13223');
}
}
)}
这是
index
文件:
@model TournamentManagementSystem.Models.Team
@{
ViewData["Title"] = "Team List";
}
<h3>@ViewData["Title"] </h3>
<hr />
<div>
<button class=" btn btn-primary " id="btnAdd">Add Team</button>
</div>
<div class="container">
<table class="table table-success table-striped table-responsive table-hover">
<thead>
<tr>
<th> Id </th>
<th> Team Name </th>
<th> Owner Name </th>
<th> Coach </th>
</tr>
</thead>
<tbody id="tblBody">
</table>
</div>
@section scripts{
<script src="/js/site.js"> </script>
}
这是控制器代码 ...
命名空间 TournamentManagementSystem.Controllers { 公共类 TeamController :控制器
{
// GET: TeamController
public readonly WebApplication11Context context;
public TeamController(WebApplication11Context db)
{
context = db;
}
public IActionResult Index()
{
return View();
}
public JsonResult GetTeams()
{
var team = context.Teams.ToList();
return Json(team);
}
}
} ...
表格显示:
方法
Json(obj)
的默认行为是将对象属性序列化为小写。
您可以使用小写的属性
$.each(response, function (Index, item) {
object += '<tr>';
object += '<td > ' + item.teamId + '</td>';
object += '<td > ' + item.teamName + '</td>';
object += '<td > ' + item.owner + '</td>';
object += '<td > ' + item.coachName + '</td>';
object += '</td>';
object += '</tr>';
});
请注意,您的代码中的
coachName
存在拼写错误。
或者,您可以使用以
Json
作为参数的 JsonSerializerOptions
方法的重载
var serializerOptions= new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
return Json(team, serializerOptions);