2012-11-03 44 views
0

我一直在這個問題上停留太久,會愛上一些幫助。傳遞來自控制器的查詢數據以查看

在視圖中,人們可以從兩個單選按鈕列表中選擇兩個項目,這兩個項目通過FormMethod.Get返回到HomeController中的Index事件。

這兩個值'parts'和'use'被查詢以返回一個結果,並通過viewbag傳遞迴視圖。然而viewbag在視圖中返回一行,如{Item = Kona,Price = 400.0000,Quantity = 2}。

鑑於我想返回item.Item,Item.Price等每個項目,所以我可以單獨使用它們。

我已經嘗試了一切,我可以找到無濟於事。 匿名類項目也拋出紅色錯誤

查看

foreach(var item in ViewBag.getstock) 
{ //Show it and then make a new line with the <BR/> 
    @item < br/> 
    //{ Item = Kona, Price = 400.0000, Quantity = 2 } 
} 

的HomeController

public ActionResult Index() 
{ 
    //this returns the entire query string 
    ViewBag.querystring = Request.QueryString; 

    //if any keys are in the url from the view 
    if (Request.QueryString.HasKeys()) 
    { 
     //extract them out so that you can use them 
     //key = the name such as Part or Use it goes Key & Value this is passed to a Viewbag 
     //get(o) is getting the value at place 0, the first value in the url 

     ViewBag.querystringvalue0 = Request.QueryString.Get(0); 
     ViewBag.querystringvalue1 = Request.QueryString.Get(1); 
    } 

    //if there is any query string 
    if (Request.QueryString.HasKeys()) 
    { 
     //pass the data to a couple of variables, 
     var parts = Request.QueryString.Get(0); 
     var use = Request.QueryString.Get(1); 

     //put them in a new query and return the results 
     ViewBag.getstock = from p in Bikeshopdb.Stocks 
     where p.PartName == parts && (p.Road == use || p.Mtn == use || p.Hybrid == use) select new 
     { 
      p.Item, p.Price, p.Quantity 
     }; 

    } 
    return View(Bikeshopdb.Stocks.ToList()); 
+0

你可以添加一些請查看代碼 - 你不應該使用查詢字符串一樣,在MVC它失敗的目的,你應該加入表單將對象返回到控制器的參數。我會建議你通過這個教程 - http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-1 – Rob

+0

嗨Rob這是相關的視圖代碼,它只是一個簡單的foreach,但我想要item.Price,Item.Item等 – netchicken

回答

0

使用視圖模型類來保存查詢結果,並傳回給視圖。例如:

的HomeController

public class MatchingStock() 
{ 

    public int ID { get; set; } 
    public string Item { get; set; } 
    public int Price { get; set; } 
    public int Quantity { get; set; } 

} 

public ActionResult Index() 
{ 

    //... 

    var list = 
     (from p in Bikeshopdb.Stocks 
     where p.PartName == parts && 
      (p.Road == use || p.Mtn == use || p.Hybrid == use) 
     select new MatchingStock() { 
      ID = p.ID, 
      Item = p.Item, 
      Price = p.Price, 
      Quantity = p.Quantity}).ToList(); 

    ViewBag.getstock = list; 

    //... 

} 

查看

@foreach (var item in (List<MatchingStock>)ViewBag.getstock) 
{ 
    @item.Item @item.Price @item.Quantity 
    <br /> 
} 
+0

Viewmodels現在對我來說,但我明白了,但它看起來像你仍然在使用HomeController和View在這裏,viewmodel適合哪裏在? – netchicken

+0

Viewmodel只是一個類,用於在特定視圖的獨特形狀中保存查詢結果。我不相信匿名類的查詢結果可以傳回給視圖。即使它可以,你如何能夠投影ViewBag.getstock以迭代結果?如果需要,可以在Controller類中定義Viewmodel類,儘管這可能不是最佳實踐。 – user1225352

+0

當你想從數據庫提取數據並在視圖中顯示時,這肯定是一種常見的情況?無論如何,感謝您的幫助,我製作了一個新班級視圖模型,並將MatchingStock插入其中。代碼很高興(感謝resharper):-),但查看返回404任何想法爲什麼? – netchicken

相關問題