你应该创建一个ViewModel
. 看下面的更新
这是代表您的页面的模型。您想要在视图中显示的元素应该存在于您的 ViewModel 中。您将在控制器中填充 ViewModel 并将其显示在页面上。
我编写了一个购物网站页面的示例,类别位于左侧,产品位于中间。两个实体将存在于不同的表中。
Example:
class MainPageViewModel
{
//this data is from a different table.
//and goes on the left of the page
public string Categories {get; set;}
//this data is also from a different table.
//and goes on the center of the page
public List<Products> Products {get; set;}
}
在你的控制器中:
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
MainPageViewModel vm = new MainPageViewModel();
vm.Categories = GetCategories();
//use the GetProducts() to get your products and add them.
vm.Products.Add(...);
return View(vm); //pass it into the page
}
string[] GetCategories()
{
DataTable data = GetDataFromQuery("SELECT * FROM Categories WHERE..");
//convert the data into a string[] and return it..
}
//maybe it has to return something else instead of string[]?
string[] GetProducts()
{
DataTable data = GetDataFromQuery("SELECT * FROM Products WHERE..");
//convert the data into a string[] and return it..
}
DataTable GetDataFromQuery(string query)
{
SqlDataAdapter adap =
new SqlDataAdapter(query, "<your connection string>");
DataTable data = new DataTable();
adap.Fill(data);
return data;
}
}
然后在你看来你适当地显示它:
@model MainPageViewModel
@{ ViewBag.Title = "MainPage"; }
<div id="left-bar">
<ul>
@foreach (var category in Model.Categories)
{
<li>@category</li>
}
</ul>
</div>
<div id="center-content">
<ul>
@foreach (var product in Model.Products)
{
<li>@product.Name</li>
<li>@product.Price..</li>
.....
}
</ul>
</div>
Update
这是关于您的评论,您提到您的数据库表和列定期更改。
我不能肯定地说,但也许你不应该每天都制作这样的表,也许你可以有更好的数据库设计,或者 RDBMS 不适合你,你应该考虑一下 NoSql数据库(如MongoDB http://www.mongodb.org/ )
尽管如此,如果您继续使用上面的代码,我建议将其放入其自己的数据层类中。
还看一下Dapper http://code.google.com/p/dapper-dot-net/它是一个非常薄的数据访问层,仅通过 SQL 查询或存储过程从数据库获取对象。 (正是您所需要的)它是由 stackoverflow 制作和使用的。