2013-03-15 39 views
0

我想這兩個方法傳遞給一個觀點:如何在傳遞兩個查詢到一個視圖

public IEnumerable<ProfitAndCostViewModel> getProfitSum() 
     { 
      var profBalance = db.Profits 
    .Where(x => x.IdUser.UserId == WebSecurity.CurrentUserId) 
    .GroupBy(x => x.IdUser.UserId) 
    .Select(x => new ProfitAndCostViewModel { ProfitSum = x.Sum(y => y.Value) }) 
    .ToList(); 
      return profBalance; 
     } 

     public IEnumerable<ProfitAndCostViewModel> getCostSum() 
     { 
      var costBalance = db.Costs 
    .Where(x => x.IdUser.UserId == WebSecurity.CurrentUserId) 
    .GroupBy(x => x.IdUser.UserId) 
    .Select(x => new ProfitAndCostViewModel { CostSum = x.Sum(y => y.Value) }) 
    .ToList(); 
      return costBalance; 
     } 
在我的ActionResult

我有這樣的:

var pcv = new ProfitAndCostViewModel(); 
      pcv.ProfModel =getProfitSum(); 
      pcv.CostModel =getCostSum(); 

      return View(pcv); 

而且在ProfitAndCostViewModel代碼是這樣的:

public double ProfitSum { get; set; } 
     public double CostSum { get; set; } 
     public double FinalBalance { get; set; } 
     public IEnumerable<ProfitAndCostViewModel> ProfModel { get; set; } 
     public IEnumerable<ProfitAndCostViewModel> CostModel { get; set; } 

這是錯誤:The model item passed into the dictionary is of type 'WHFM.ViewModels.ProfitAndCostViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [WHFM.ViewModels.ProfitAndCostViewModel]」`

+0

檢查您傳遞給視圖和模型的模型一個視圖,這是不同的 – Sergio 2013-03-15 09:32:55

回答

3

它看起來像你的看法是強類型到IEnumerable<ProfitAndCostViewModel>

@model IEnumerable<ProfitAndCostViewModel> 

但在這裏要傳遞一個ProfitAndCostViewModel實例吧:

var pcv = new ProfitAndCostViewModel(); 
pcv.ProfModel =getProfitSum(); 
pcv.CostModel =getCostSum(); 
return View(pcv); 

所以,你應該修正模型到您的查看輸入:

@model ProfitAndCostViewModel 
+0

我使這個像你說的,但現在的錯誤是這樣的:oreach語句不能對'WHFM.ViewModels.ProfitAndCostViewModel'類型的變量操作,因爲'WHFM.ViewModels.ProfitAndCostViewModel'不包含'GetEnumerator的公共定義' – Krasimir 2013-03-15 09:35:01

+0

然後修復您的foreach:@foreach(Model.ProfModel中的var item){...}而不是'foreach(Model中的var item)'。如果您在視圖中使用「CostModel」屬性,則相同。這是基本的C#。 – 2013-03-15 09:35:51

相關問題