将数据从SQL数据库加载到C#表执行时间问题
问题描述:
我是否试图从数据库中将数据加载到.cshtml页面的表中。出于某种原因,数据库中的数据以纯文本形式加载到页面的顶部,而不是整洁地填充表格。谁能告诉我为什么可以这样做?是否有一些我缺少的执行时机制?将数据从SQL数据库加载到C#表执行时间问题
<div id="log_container" display="inline-block" margin="100">
<table id="log_table">
<tr><th>ID</th><th>Filename</th><th>Mark In</th><th>Mark Out</th><th>Note</th></tr>
@using (SqlConnection connection = new SqlConnection(connString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM dbo.TestTable", connection);
command.CommandType = CommandType.Text;
adapter.SelectCommand = command;
DataSet dataSet = new DataSet("TestTable");
adapter.Fill(dataSet);
dataSet.Tables.Add("TestTable");
connection.Close();
foreach(DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
Response.Write("<tr>");
Response.Write("<td>" + row.ItemArray[0] + "</td>");
Response.Write("<td>" + row.ItemArray[1] + "</td>");
Response.Write("<td>" + row.ItemArray[2] + "</td>");
Response.Write("<td>" + row.ItemArray[3] + "</td>");
Response.Write("<td>" + row.ItemArray[4] + "</td>");
Response.Write("</tr>");
}
}
}
</table>
</div>
答
Response.Write立即写入连接,简化了为输出组装网页的过程。它不应该在.cshtml中使用,因为输出在Razor模板返回之前发生。
要做更优化的方式,我建议将连接等移动到控制器中,而不是直接在.cshtml中,但为了使代码按照您的预期工作,您只需将其更改为如下。删除Reponse.Write并将其替换为Razor语法。
@<div id="log_container" display="inline-block" margin="100">
<table id="log_table">
<tr><th>ID</th><th>Filename</th><th>Mark In</th><th>Mark Out</th><th>Note</th></tr>
@using (SqlConnection connection = new SqlConnection(connString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM dbo.TestTable", connection);
command.CommandType = CommandType.Text;
adapter.SelectCommand = command;
DataSet dataSet = new DataSet("TestTable");
adapter.Fill(dataSet);
dataSet.Tables.Add("TestTable");
connection.Close();
foreach(DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
<tr>
<td>@row.ItemArray[0]</td>
<td>@row.ItemArray[1]</td>
<td>@row.ItemArray[2]</td>
<td>@row.ItemArray[3]</td>
<td>@row.ItemArray[4]</td>
</tr>
}
}
}
</table>
</div>
工作完美!感谢您的好解释和建议。 – elizzmc 2014-09-12 17:56:21