2012-09-02 41 views
4

我使用web-forms開發網站,現在我有一個使用MVC3框架和Rzor的項目。我的問題是關於MVC中的一些基本設計模式。我有一個網頁,在左邊我會從SQL表中拉類別,在中心我會查詢另一個SQL表格,以及更多的頁面。asp.net mvc和sql查詢

所以我的問題是...什麼是將數據放入一個網頁的最佳方式,所有這些查詢都是完全獨立的,是否需要爲每個查詢創建新的模型?還是有更好的方法呢?

in WebForms我使用了用戶控件,其中每個用戶控件都有自己的設計& Sql查詢。我聽說過在MVC中使用部分視圖,但我不確定,我想我很難理解如何使用不同的查詢將數據放入一個網頁&顯示網頁上的輸出。

謝謝

+0

根據您對Gideon的評論,您當然可以做到這一點。但這不是大多數人的做法。大多數人使用ORM來獲取數據,因爲它簡化了整個過程。但你可以自由地編寫任何代碼,只要你認爲合適 –

回答

8

您應該創建一個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製作和使用的。

+0

感謝您的輸入,它確實有意義,但是我想問問什麼是將數據導入mvc的最佳方式。在webform中,我用於在數據表中存儲數據並將數據表綁定到控件。我在mvc中看到的所有示例都是使用linq to sql或ado。淨實體框架,我必須將所有表拖入模型,VS將爲我創建類。現在,我只想簡單地將數據拉到像web窗體,簡單的SQL查詢,並有一個類返回數據,如何做到這一點,而無需做和表拖或使用嚮導。我有大約100張桌子。謝謝 – highwingers

+0

換句話說,提供一個簡單的例子並且告訴我如何通過抓取一個sql表來填充下面是一件很棒的事情。vm.Catagories = //從 – highwingers

+0

@highwingers中獲取你的類別你的意思是你想執行你的自己的SQL與'SqlConnection','SqlDataAdapter','SqlCommand'等類? **你有什麼數據庫?** Sql Server? – gideon