2017-06-12 34 views
1

我確信我只是在考慮這個問題太多,但我正在嘗試獲取一個列表,除了一件事情之外,其他所有工作都可以使用。而且我知道它爲什麼會這樣做,它會得到foreach的最後一項,它被分配到循環的外部並返回一個項目。但我想要歸還所有這些。 我在做什麼錯?Foreach不會將每個項目從foreach添加到ViewModel

var cheeses = _repository.GetAllYearSetupIds(); 
var gouda = new CollectionsManagementViewModel(); 
var yearSetupId = 0; 
foreach(var cheddar in cheeses) 
{ 
    yearSetupId = cheddar.YearSetupId; 
    gouda = _repository.GetOverdueBalances(page, pageLength, yearSetupId, balancefilter, sort, direction == Constants.ascending, spreadsheetType); 
    gouda.Title = title + " Management"; 
}  
return View("CollectionsManagement", gouda); 
+0

這是不可能真正理解你的問題沒有好的[MCVE。但是看起來你有一個返回單個對象的方法。是什麼讓你認爲它有可能做任何事情,但做到這一點?即_「返回所有人」_?即使它確實收回了收藏品,你會怎麼做?你將需要更具體。修復你的問題,使其包含一個很好的MCVE,並且更好地描述代碼現在做什麼,你想要它做什麼,以及具體哪些_specifically_你有困難計算出來。 –

+0

這是什麼'View'類?你的意思是用[tag:asp.net-mvc]標記你的問題,而不是[tag:model-view-controller]? (我看到謝爾蓋改變了標籤,就像我發佈這條評論一樣......所以人們希望這是正確的。如果標籤正確,你的問題會更清楚。) –

+0

foreach不支持cheese數據類型 –

回答

2

目前,你在你的循環每次迭代更新的CollectionsManagementViewModel命名gouda單個實例。循環gouda將具有上次迭代的值。

您應該在每次迭代中創建CollectionsManagementViewModel的新實例,並將此實例添加到視圖模型列表中。當然,命名應該是有意義的:

// list of models, because you want ALL of them 
var managementModels = new List<CollectionsManagementViewModel>(); 
var setupIds = _repository.GetAllYearSetupIds(); 

foreach(var setupId in setupIds) 
{ 
    // new model created for each setup id 
    var managementModel = _repository.GetOverdueBalances(page, pageLength, 
      setupId.YearSetupId, balancefilter, 
      sort, direction == Constants.ascending, 
      spreadsheetType); 

    managementModel.Title = title + " Management"; 
    managementModels.Add(managementModel); // add model to list 
} 

// pass collection to view 
return View("CollectionsManagement", managementModels); 
+1

謝謝,這真的有所幫助。我很不確定如何去做,我被自己的大腦絆倒了。 – CheezStix

+0

傳入字典的模型項目類型爲'System.Collections.Generic.List'1 [CollectionsManagementViewModel]',但是此字典需要類型爲'CollectionsManagementViewModel'的模型項目。 – CheezStix

0

嗨希望下面的代碼可能會有助於您

var cheeses = _repository.GetAllYearSetupIds(); 
var lstgouda = new List<CollectionsManagementViewModel>(); //make a list 
var yearSetupId = 0; 
foreach(var cheddar in cheeses) 
{ 

    var gouda = new CollectionsManagementViewModel(); 
    yearSetupId = cheddar.YearSetupId; 
    gouda = _repository.GetOverdueBalances(page, pageLength, yearSetupId, balancefilter, sort, direction == Constants.ascending, spreadsheetType); 
    gouda.Title = title + " Management"; 
    lstgouda.add(gouda); //add it to list 
}  
return View("CollectionsManagement", lstgouda); 

感謝 KARTHIK

相關問題