2017-09-15 37 views
-2

我有這種方法,應顯示最受歡迎/最喜愛的產品和順序降序根據每個產品的數量總和。儘管它仍然需要測試。我需要從控制器調用這個方法ProductPop()進入View。未鏈接到控制器如何顯示在查看傳遞從controller.MVC項目列表

public class AnalysisController : Controller 
{ 
    public List<Order_Detail> ProductPop() 
    { 
     List<Order_Detail> result = new List<Order_Detail>(); 
     result.GroupBy(l => l.ProductName).Select(cl => new Order_Detail 
     { 
      ProductName = cl.First().ProductName, 
      Quantity = cl.Sum(c => c.Quantity) 
     }).OrderByDescending(k=>k.Quantity).ToList(); 

     return result; 
    } 
} 

這是我在我看來(這種觀點是另一個控制器只返回一個視圖的空指標法):

@using ProjectName.Controllers; 
@{ 
    AnalysisController AC = new AnalysisController(); 
    ViewBag.Title = "Index"; 
} 

@foreach(var od in ProductPop()) 
{ 
    <table> 
     <tr> 
      <th> 
       Product Name 
      </th> 
      <th> 
      Quantity 
      </th> 
     </tr> 
     <tr> 
      <td> 
       @od.ProductName 
      </td> 
      <td> 
       @od.Quantity 
      </td> 
     </tr> 
    </table> 
} 

如果有任何參考/建議。我會格萊迪欣賞它。謝謝!

+1

你有沒有試過閱讀基地ASP.NET MVC教程? – Marusyk

回答

0

你不應該創建一個instan像你這樣的控制器,而是將模型傳遞給你的視圖。您可以直接將List<Order_Detail>作爲模型傳遞,也可以將List<Order_Detail>包裝在模型中,就像我在下面的代碼示例中一樣。

首先,創建模型中的一個新的類:

public class ProductPopModel { 
    public List<Order_Detail> Result { get; set; } 
} 

然後,在你Analysis控制器內部的Index行動,創建一個ProductPopModel實例填充它:

public class AnalysisController : Controller 
{ 
    public ActionResult Index() { 
     List<Order_Detail> result = new List<Order_Detail>(); 
     //The code below will never return anything because you are peforming operations on an empty list 
     result.GroupBy(l => l.ProductName).Select(cl => new Order_Detail 
     { 
      ProductName = cl.First().ProductName, 
      Quantity = cl.Sum(c => c.Quantity) 
     }).OrderByDescending(k=>k.Quantity).ToList(); 
     var model = new ProductPopModel { 
      Result = result 
     }; 

     return View(model); 
    } 
} 

請注意我在此指出,您的result將始終爲空,因爲您在空的List<Order_Detail>上執行操作GroupBySelect

於是最後,在你看來,與@model指定型號類型:

@model ProductPopModel 
@{ 
    ViewBag.Title = "Index"; 
} 

@foreach(var od in Model.Result) 
{ 
    <table> 
     <tr> 
      <th> 
       Product Name 
      </th> 
      <th> 
      Quantity 
      </th> 
     </tr> 
     <tr> 
      <td> 
       @od.ProductName 
      </td> 
      <td> 
       @od.Quantity 
      </td> 
     </tr> 
    </table> 
} 
1

回報在指數的ActionResult和您的視圖中使用@model

控制器的OrderDetail數據

[HttpGet] 
public ActionResult Index() 
{ 
    return View(ProductPop()); 
} 

查看

@model Order_Detail; 

@foreach(var od in ProductPop()) 
{ 
    <table> 
     <tr> 
      <th> 
       Product Name 
      </th> 
      <th> 
      Quantity 
      </th> 
     </tr> 
     <tr> 
      <td> 
       @model.ProductName 
      </td> 
      <td> 
       @model.Quantity 
      </td> 
     </tr> 
    </table> 
} 
相關問題