2015-05-19 128 views
0

我有一个名为“PlanObjectsViewModel”的视图模型。我需要在我的while循环中添加结果到PlanObjectsViewModel的一个实例。我尝试了下面的方法..是那个错误?我得到一个异常,称为;如何通过viewmodel查看

传递到词典中的模型产品'MvcApp.ViewModel.PlanObjectsViewModel'类型的,但是这需要字典类型“System.Collections.Generic.IEnumerable`1 [MvcApp.ViewModel.PlanObjectsViewModel]”的一个模型项。

var model2 = model1.GroupBy(t => t.Type).Select(g => new PlanBaseTypedObjects 
{ 
    Id = g.Key, 
    ObjectDetails = g 
}); 

int Type1 = 0; 
int Type2 = 0;   

double? temp = 0; 

foreach (var item in model2) 
{ 
    if(item.Id==1) 
     Type1 = item.ObjectDetails.Count(); 

    if (item.Id == 2) 
     Type2 = item.ObjectDetails.Count(); 
} 

Random rand = new Random(); 

var final = new PlanObjectsViewModel(); // want to add data to this view model 

while (budget > temp) 
{ 
    if (Type1 != 0) { 
     int randi = rand.Next(0, Type1); 

     foreach (var item in model2) 
     { 
      if (item.Id == 1) { foreach (var x in item.ObjectDetails) { 
       if (x.Id == randi) 
        final.Id = x.Id;// i don't know,whether this is a correct way to 
            //add data row to the model 
       temp=temp+x.Price; 
      } 
      } 
     } 
    } 

    if (Type2 != 0) 
    { 
     int randi = rand.Next(0, Type2); 

     foreach (var item in model2) 
     { 
      if (item.Id == 2) 
      { 
       foreach (var x in item.ObjectDetails) 
       { 
        if (x.Id == randi) 
         final.Id = x.Id; 
        temp = temp + x.Price; 
       } 
      } 
     } 
    } 
} 
return View(model1); 

在我看来,我有;

@model IEnumerable<MvcApp.ViewModel.PlanObjectsViewModel> 

任何人都可以解释为什么?如果我这样做是错误的,最好的办法是什么?谢谢。

+3

是什么类型MODEL1?错误表示这是一个单一的值,而不是可枚举的。 –

+1

如果您最终将'model1'传递给视图,那么使用'model2'进行循环和计算有什么意义? – ekad

+0

对不起! final是一个传递给view..not model1 –

回答

0

您正在等待一个集合,但您将单个项目传递给该视图。

MvcApp.ViewModel.PlanObjectsViewModel =对象 System.Collections.Generic.IEnumerable[MvcApp.ViewModel.PlanObjectsViewModel] =集合对象

这个变化

@model IEnumerable<MvcApp.ViewModel.PlanObjectsViewModel>

@model MvcApp.ViewModel.PlanObjectsViewModel