我有一个简单的 MVC 应用程序,它从数据库表中获取数据并将其显示在 html 表中。当我尝试使用服务器端处理时,数据被返回,但它显示在浏览器中而不是我的表格中。
这是脚本:
<script>
$(document).ready(function () {
$('#patients').dataTable({
"bServerSide":true,
"bProcessing":true,
"sAjaxSource": '@Url.Action("Index","Patient")',
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
</script>
这是html表:
<table width="100%" id="patients">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
这是我的控制器操作方法:
public ActionResult Index()
{
List<Patient> patients = new List<Patient>();
using (SqlConnection conn = new SqlConnection("Server=server;Database=db;Trusted_Connection=True"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Patient",conn))
{
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
patients.Add(new Patient { FirstName = reader["FirstName"].ToString(), LastName = reader["LastName"].ToString() });
}
}
}
return Json(new
{
aaData = patients.Select(x=> new[] {x.FirstName,x.LastName})
},JsonRequestBehavior.AllowGet);
}
}
这是浏览器中显示的 JSON:
{"aaData":[["Tom","Jones"],["Jerry","Jones"],["Jack","Roberts"],["Harry","Truman"],["Bill","Clinton"],["Barrack","Obama"],["George","Bush"],["Ed","Lee"],["Michael","Jordan"],["James","Caan"],["Rick","Reilly"],["Johhny","B.Goode"]]}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
</div>
<div class="float-right">
<section id="login">
@Html.Partial("_LoginPartial")
</section>
<nav>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Patients","Index","Patient")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</nav>
</div>
</div>
</header>
<div id="body">
@RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
@RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/table")
@RenderSection("scripts", required: false)
</body>
</html>