C# 将SQL数据库中的数据加载到C表执行定时问题
我正在尝试将数据从数据库加载到.cshtml页面中的表中。出于某种原因,数据库中的数据以纯文本形式加载到页面顶部,而不是整齐地填充表。有人能告诉我为什么会这样吗?有没有我错过的执行计时机制C# 将SQL数据库中的数据加载到C表执行定时问题,c#,sql-server,asp.net-mvc-3,razor,C#,Sql Server,Asp.net Mvc 3,Razor,我正在尝试将数据从数据库加载到.cshtml页面中的表中。出于某种原因,数据库中的数据以纯文本形式加载到页面顶部,而不是整齐地填充表。有人能告诉我为什么会这样吗?有没有我错过的执行计时机制 <div id="log_container" display="inline-block" margin="100"> <table id="log_table"> <tr><th>ID</th><th>Filenam
<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>
响应。立即写入写入到连接,缩短了为输出组装网页的过程。它不应该在.cshtml中使用,因为输出发生在Razor模板返回之前 为了以更优化的方式进行操作,我建议将您的连接等移动到控制器中,而不是直接移动到.cshtml中,但是为了使您的代码按预期工作,您只需要按如下方式进行更改。删除响应。写入并替换为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>
那很有效!谢谢你的解释和建议。