我正在创建一个asp.net mvc2项目。我想显示数据表中的数据但是当我运行项目时,它不会显示我想要显示的数据。
这些是我的代码:
HomeController.cs
public ActionResult Index()
{
connection connect = new connection();
string query = "SELECT Event_Name FROM tbl_Event WHERE Event_ID=2";
return View(connect.SelectRecord(query));
}
的Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Data.DataTable>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Index</h2>
<%Model.Rows[0].ItemArray[0].ToString(); %>
</asp:Content>
connection.cs
internal DataTable SelectRecord(string query)
{
try
{
OpenConnection();
cmd = new SqlCommand(query, conn);
adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd = null;
CloseConnection();
}
}
我想在Index.aspx中显示这一行&lt;%Model.Rows [0] .ItemArray [0] .ToString(); %GT;
我在此链接中尝试了 Kurt Schindler 的答案: Displaying standard DataTables in MVC 但它没有指定如何显示数据表中的特定数据。请帮我。我使用datatable在asp.net视图上显示数据的原因是因为我很乐意将它用作我的临时数据存储。
答案 0 :(得分:1)
试试这个
public ActionResult Index()
{
connection connect = new connection();
string query = "SELECT Event_Name FROM tbl_Event WHERE Event_ID=2";
return View(connect.SelectRecord(query));
}
internal DataTable SelectRecord(string query)
{
try
{
OpenConnection();
cmd = new SqlCommand(query, conn);
adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd = null;
CloseConnection();
}
}
这是查看
查看:(强类型为System.Data.DataTable)
<table border="1">
<thead>
<tr>
<%foreach (System.Data.DataColumn col in Model.Columns) { %>
<th><%=col.Event_Name%></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>