将数据从SQL数据库加载到C#表执行时间问题



我是否试图将数据从数据库加载到.cs.html页面中的表中。出于某种原因,数据库中的数据以纯文本形式加载到页面顶部,而不是整齐地填充表。有人能告诉我为什么会这样吗?有没有我遗漏的执行时间机制?

<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立即写入连接,缩短了组装网页以进行输出的过程。它不应该在.cs.html中使用,因为在返回Razor模板之前会发生输出。

为了以更优化的方式进行操作,我确实建议将您的连接等移动到控制器中,而不是直接在.cs.html中,但为了使您的代码按预期工作,您只需要按如下方式进行更改。删除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>

最新更新