您應該創建一個ViewModel
。 看看下面的更新
這是一個模型,代表您的網頁。您想要在視圖中顯示的元素應存在於ViewModel中。您將在您的控制器中填充ViewModel並將其顯示在頁面上。
我已經寫了一個購物網站頁面的例子,左邊的分類和中心的產品。兩個實體都將存在於不同的表格中。
實施例:
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>
更新
這是關於您的評論,您提到您的數據庫表和列經常更改。
我不能肯定地說,但也許你不應該每天都這樣做表格,也許有更好的數據庫設計你可能有,或者RDBMS不適合你,你應該看看一個NoSql數據庫(如MongoDB)
不過,如果你繼續上面的代碼,我建議把它放到它自己的數據層類中。
另請參閱Dapper這是一個非常薄的數據訪問層,它只是使用sql查詢或存儲過程從數據庫中獲取對象。 (正是你需要的)它是由stackoverflow製作和使用的。
根據您對Gideon的評論,您當然可以做到這一點。但這不是大多數人的做法。大多數人使用ORM來獲取數據,因爲它簡化了整個過程。但你可以自由地編寫任何代碼,只要你認爲合適 –