我是MVC的新手,尝试编写一个简单的MVC 3应用程序,该应用程序在模型中读取客户数据并使用控制器将其返回到视图。阅读器显示它有行,但当加载到表格并作为模型传递给视图时,它为空。我需要一个简单的解决方案,可以将
以下是代码:
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);
}
}
}
DataReader
或DataTable
传递给视图。也不要将DataReader
或DataTable
传递给 ViewModel。创建一个代表您需要处理的数据的 POCO - 这称为模型,将其传递给知道如何将该数据转换为可呈现内容的类 - 这称为 ViewModel,然后将其传递到您的视图中。为了使您的生活更轻松,请尝试使用 Entity Framework。 - Jay