【问题标题】:C# SQL Database to HTML TableC# SQL 数据库到 HTML 表
【发布时间】:2019-04-06 14:39:47
【问题描述】:

我正在尝试从我的 SQL 表中获取数据以显示到我想显示表中的内容的视图页面上

我目前可以使用下面的代码读取数据库中的项目

SqlConnection connection = new SqlConnection(VV);

using (connection)
{
  //LIMIT 5 DESC from ID which shows last 5 work outs 
  SqlCommand myCommand = new SqlCommand("SELECT * FROM Strength", connection);
  connection.Open();

  SqlDataReader read = myCommand.ExecuteReader();
  if (read.HasRows)
  {
    while (read.Read())
    {
      Id = read["Id"].ToString();
      System.Diagnostics.Debug.WriteLine(Id);

      Weight = read["Weight"].ToString();                    
      System.Diagnostics.Debug.WriteLine(Weight);

      Rep = read["Rep"].ToString();
      System.Diagnostics.Debug.WriteLine(Rep);
    }
  }
  else
  {
    Console.WriteLine("nothing");
  }
  read.Close();
}

现在我想在视图上的 HTML 表格中显示它。我已经尝试了一些东西,例如

 ViewBag.HtmlStr = "<table class='table table-striped top-buffer'"
                 + "style='width:300px'>"
                 + "<tr><th>Weight(KG)</th><th>Reps</th></tr>"
                 + "<tr><td>" + TableWeight + "</td>"
                 + "</tr><tr><td>" + TableRep + "</td></tr></table>";

但是它只给了我一排。

有什么建议吗? 非常感谢

【问题讨论】:

  • while (read.Read()) 中的代码将为数据库返回的每一行执行。您需要为每一行创建一个对象列表和一个新项目到列表中,然后将该列表发送到您的视图。
  • 哦,我强烈建议您不要将 HTML 从控制器传递到视图。你应该传递你的模型(数据),而不是 HTML
  • 创建一个模型,然后在您的视图中使用该模型使用 Razor 创建 html 表。

标签: c# asp.net-mvc


【解决方案1】:
using (connection)
{
  //LIMIT 5 DESC from ID which shows last 5 work outs 
  SqlCommand myCommand = new SqlCommand("SELECT * FROM Strength", connection);
  connection.Open();

  SqlDataReader read = myCommand.ExecuteReader();

  string result = "<table class='table table-striped top-buffer'" 
                + "style='width:300px'>" 
                + "<tr><th>Weight(KG)</th><th>Reps</th></tr>";               

  if (read.HasRows)
  {
    while (read.Read())
    {
      Id = read["Id"].ToString();
      System.Diagnostics.Debug.WriteLine(Id);

      Weight = read["Weight"].ToString();
      System.Diagnostics.Debug.WriteLine(Weight);

      Rep = read["Rep"].ToString();
      System.Diagnostics.Debug.WriteLine(Rep);

      result += "<tr><td>" + Weight + "</td>"
             +  "</tr><tr><td>" + Rep + "</td></tr>";
    }
  }
  else
  {
    Console.WriteLine("nothing");
  }
  read.Close();

  ViewBag.HtmlStr = result + "</table>";
}

您必须考虑到您的数据源包含多行,并且您应该将每一行作为 TR 添加到表中。

【讨论】:

  • 混合 HTML 和数据访问代码不是一个好主意。您应该从 SqlDataReader 创建一个对象列表,然后将该列表发送到您的视图。
  • @RuiJarimba 我同意,但如果他想使用这种方法,我会向他展示他的代码有什么问题。
  • 谢谢@Amin,它现在可以工作了。另一个快速的问题,为什么混合 HTML 和数据访问代码不是一个好主意?
  • 不客气。 HTML 格式是您的表示格式,它与您的数据结构无关。所以你应该在你的控制器中创建一个好的数据,你应该在你的视图中用你想要的格式来表示它。
  • @Leon 关注点分离。请阅读 Model-View-Controller (MVC) 或观看一些视频,例如 Introduction to ASP.NET MVC
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 2016-06-21
相关资源
最近更新 更多