I am creating an asp.net mvc2 project. I wanted to display data from a datatable but when i run the project, it does not display the data i wanted to display.
these are my codes:
public ActionResult Index()
{
connection connect = new connection();
string query = "SELECT Event_Name FROM tbl_Event WHERE Event_ID=2";
return View(connect.SelectRecord(query));
}
<%@ 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>
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();
}
}
<%Model.Rows[0].ItemArray[0].ToString(); <%Model.Rows [0] .ItemArray [0] .ToString();中 。 %>
I have tried the answer of in this link: Displaying standard DataTables in MVC but it does not specify how to display a specific data from the datatable. 的答案: 在MVC中显示标准数据表,但未指定如何从数据表中显示特定数据。 Please help me. The reason I use datatable to display data on asp.net views is because I am comfortable using it as my temporary storage of data.
Try this
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();
}
}
Here is view
View: (strongly typed as 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>
Check this link : http://weblogs.asp.net/gunnarpeipman/archive/2011/11/19/asp-net-mvc-simple-view-to-display-contents-of-datatable.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.