我已将数据从数据库表存储到DataTable dt。 DataTable正在控制器中填充。我正在尝试通过分页在HTML页面上获取DataTable数据。但是不知何故,数据没有被打印出来。可能是因为视图未从Controller访问DataTable。这是我所做的:
控制器:
int pageindex = 0;
public DataTable GetRecords()
{
pageindex = pageindex + 20;
string constr = ConfigurationManager.ConnectionStrings["BOConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Invoice ORDER BY OrderId ASC OFFSET (@pageindex) ROWS FETCH NEXT 20 ROWS ONLY"))
{
cmd.Parameters.AddWithValue("@pageindex", pageindex);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
查看:
@using System.Data;
@using System.Data.DataTable;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Reports</title>
</head>
<body>
<div>
<a href=@Url.Action("GetRecords", "Records")>Print Records</a><br />
<table border="1" cellpadding="5">
<thead>
<tr>
@foreach (System.Data.DataColumn col in Model.Columns)
{
<th>@col.Caption</th>
}
</tr>
</thead>
<tbody>
@foreach (System.Data.DataRow row in Model.Rows)
{
<tr>
@foreach (var cell in row.ItemArray)
{
<td>@cell.ToString()</td>
}
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
但是它抛出错误:“对象引用未设置为对象实例。”在Models.Columns中。我认为这是因为没有填充(或引用)DataTable。我怎样才能做到这一点?如何在View的Controller中引用DataTable dt?如果控制器中有多个数据表怎么办?