如何传递viewmodel到视图
本文关键字:视图 viewmodel 何传递 | 更新日期: 2023-09-27 17:49:42
我有一个名为"PlanObjectsViewModel"的视图模型。我需要在我的while循环中添加结果到PlanObjectsViewModel的实例。我试着遵循这个方法,这错了吗?我得到一个异常,叫做;
传入字典的模型项是类型为
'MvcApp.ViewModel.PlanObjectsViewModel'
的,但是这个字典需要一个类型为'System.Collections.Generic.IEnumerable ' 1[mvcap . 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>
谁能解释一下这是为什么?如果我这样做是错误的,最好的方法是什么??谢谢你。
你期待一个集合,但你传递了一个单独的项目给视图。
MvcApp.ViewModel.PlanObjectsViewModel
= objectSystem.Collections.Generic.IEnumerable[MvcApp.ViewModel.PlanObjectsViewModel]
=对象集合
修改
@model IEnumerable<MvcApp.ViewModel.PlanObjectsViewModel>
@model MvcApp.ViewModel.PlanObjectsViewModel