我是 MVC 的新手,正在尝试编写一个简单的 MVC 3 应用程序,该应用程序读取模型类中的客户数据并使用 Controller 将其返回给 View 。阅读器显示它有行但是当加载到表并作为模型传递给 View 时,它为空。我需要一个简单的解决方案来传递 DataTable
来查看或传递 DataReader
来查看我可以转换为 DataTable
的位置。
代码如下:
namespace MvcApplication3.Models
{
public class Customer
{
public DataTable GetCustomers(OdbcDataReader rds)
{
String ConString = "DSN=Northwind;Uid=;Pwd=;";
String SQL = "SELECT * FROM CUSTOMERS";
DataTable tbl = new DataTable();
using (OdbcConnection con = new OdbcConnection(ConString))
{
con.Open();
OdbcCommand cmd = new OdbcCommand(SQL, con);
rds = cmd.ExecuteReader();
}
}
}
}
namespace MvcApplication3.Controllers
{
public class DefaultController : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
Customer cs = new Customer();
OdbcDataReader rd = new OdbcDataReader();
cs.GetCustomers(rd);
DataTable tb = new DataTable();
tb.Load(rd);
return View(tb);
}
}
}
最佳答案
对于 Controller :
public ActionResult Index()
{
DataTable dt = GetData();
return View(dt);
}
然后在 View 中:
@model System.Data.DataTable
@using System.Data;
...................... ..................... …………
<table class="table table-hover">
<thead>
<tr>
@foreach (DataColumn col in Model.Columns)
{
<th>@col.ColumnName</th>
}
</tr>
</thead>
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@foreach (DataColumn col in Model.Columns)
{
<td>@row[col.ColumnName]</td>
}
</tr>
}
</tbody>
</table>
关于c# - 如何通过 DataReader/DataTable 来查看?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17869366/