我是否尝试将数据库中的数据加载到.cshtml页面中的表中。出于某种原因,数据库中的数据以纯文本形式加载到页面顶部,而不是整齐地填充表格。谁能告诉我为什么会这样做?是否有一些我缺少的执行时间机制?
<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>
答案 0 :(得分:1)
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>