2017-06-12 8 views
1

私はこれについてあまりにも多く考えていると確信していますが、リストを取得しようとしています。そして、なぜそれがそれをやっているのか知っています。それは、ループの外側に割り当てられ、その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と、コードが現在何をしているか、代わりに何をしたいのか、そして何が問題になっているのかをはっきりと説明してください。 –

+0

ここに 'View'クラスとは何ですか? [tag:model-view-controller]ではなく[tag:asp.net-mvc]であなたの質問にタグを付けることを意味しましたか? (Sergeyがこのコメントを投稿したのと同じように、タグが変更されているのを見ています...正しいものとタグが付いていれば、あなたの質問はより明確になります) –

+0

foreachはチーズのデータ​​型では機能しません –

答えて

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); 

おかげ カルティク

関連する問題