在ASP和C#中制作一个没有格式的列表
本文关键字:一个 有格式 列表 ASP | 更新日期: 2024-09-24 04:26:42
我正在尝试使用C#实现最简单的查询,并在ASP.NET中列出它们。我对此有点困惑。我熟悉C#,但不确定如何在ASP.NET中列出它们,因为我刚刚开始使用这种语言。
对,我有一张桌子叫食谱。我正在尝试检索Recipe_ID和Name并列出它们。一个在另一个下面。无格式设置。
1 item1
2 item2
3 item3
etc...
任何帮助都会很棒。我为这个愚蠢的问题道歉。我可能只是没有研究正确的东西。
C#
private void loadRecipe()
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)'v11.0; AttachDbFilename=C:'Users'Donald'Documents'Visual Studio 2013'Projects'DesktopApplication'DesktopApplication'Student_CB.mdf ;Integrated Security=True");
con.Open();
try
{
//Fetching top recipe
string query = ("SELECT Recipe_ID, Recipe_Name FROM Recipe");
SqlCommand cmd = new SqlCommand(query, con);
[[[what goes here]]]
}
catch (Exception)
{
}
con.Close();
}
ASP.NET
[[[What do i need for this]]]
欢迎光临。每个人都从某个地方开始。有很多更好的方法可以做到这一点——这本质上是一种破解,将所有内容加载到字符串中并填充标签。但是,它将向您展示如何访问数据。查看ASP GridView。
C#
private void loadRecipe()
{
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)'v11.0; AttachDbFilename=C:'Users'Donald'Documents'Visual Studio 2013'Projects'DesktopApplication'DesktopApplication'Student_CB.mdf ;Integrated Security=True");
try
{
//Fetching top recipe
string query = ("SELECT * Recipe_ID, Recipe_Name FROM Recipe");
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Connection = conn;
cmd.Connection.Open();
String body;
SqlDataReader dr = cmd.ExecuteReader();
int count = 0;
if(dr.HasRows){
while(dr.Read()){
body += count++ + " " + dr["Body"].ToString() + "<br />";
}
}
myLabel.Text = body;
}
catch (Exception){}
conn.Close();
}
ASP.NET
<asp:Label runat="server" ID="myLabel" Text=""></asp:Label>
第一次重写LoadRecipe方法:
private DataTable LoadRecipe()
{
DataTable recipe = new DataTable();
var connectionString = @"Data Source=(LocalDB)'v11.0; AttachDbFilename=C:'Users'Donald'Documents'Visual Studio 2013'Projects'DesktopApplication'DesktopApplication'Student_CB.mdf ;Integrated Security=True"
using(var con = new SqlConnection(connectionString){
con.Open();
try
{
//Fetching top recipe
var query = ("SELECT Recipe_ID, Recipe_Name FROM Recipe");
var cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
recipe.Load(dr);
}
catch (Exception ex)
{
throw; //(or logg)
}
finally // ensure that connection would be closed at any case
{
con.Close();
}
}
return recipe;
}
在您的控制器中(如果您使用ASP MVC)
public ActionResult Index()
{
var recepy = LoadRecipe();
return View(recepy); //passing the DataTable to the View
}
并且在您的视图
@model System.Data.DataTable
<table border="1">
<thead>
<tr>
<%foreach (System.Data.DataColumn col in Model.Columns) { %>
<th><%=col.Caption %></th>
<%} %>
</tr>
</thead>
<tbody>
<% foreach(System.Data.DataRow row in Model.Rows) { %>
<tr>
<% foreach (var cell in row.ItemArray) {%>
<td><%=cell.ToString() %></td>
<%} %>
</tr>
<%} %>
</tbody>
</table>
这将把DataTable传递给View,并将它们表示为表