【发布时间】: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