如何将viewmodel传递给视图

时间:2015-05-19 17:31:39

标签: c# asp.net-mvc asp.net-mvc-viewmodel

我有一个名为" PlanObjectsViewModel"的视图模型。我需要将我的while循环中的结果添加到PlanObjectsViewModel的实例中。我尝试了以下方法。这是错的吗?我收到了一个名为;

的异常
  

传递到字典中的模型项的类型为pandas.read_sql_query,但此字典需要类型为' System.Collections.Generic.IEnumerable`1 [MvcApp.ViewModel.PlanObjectsViewModel]&#的模型项。 39;

'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);
谁能解释为什么会这样?如果我这样做是错误的,那么最好的方法是什么?谢谢。

1 个答案:

答案 0 :(得分:0)

您期待收藏,但您会将单个项目传递给视图。

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

更改此

@model IEnumerable<MvcApp.ViewModel.PlanObjectsViewModel>

@model MvcApp.ViewModel.PlanObjectsViewModel