简体   繁体   English

如何在视图模型中传递视图

[英]how to pass viewmodel in to view

I have a viewmodel called "PlanObjectsViewModel". 我有一个名为“ PlanObjectsViewModel”的视图模型。 I need to add results inside of my while loop to an instance of PlanObjectsViewModel.I tried following approach..Is that wrong?? 我需要将while循环内的结果添加到PlanObjectsViewModel的实例中。我尝试了以下方法。 I'm getting an exception called; 我收到一个异常叫;

The model item passed into the dictionary is of type 'MvcApp.ViewModel.PlanObjectsViewModel' , but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MvcApp.ViewModel.PlanObjectsViewModel]'. 传递到字典中的模型项的类型为'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);

In my view i have; 我认为我有;

@model IEnumerable<MvcApp.ViewModel.PlanObjectsViewModel>

can anyone explain why is that?? 谁能解释为什么?? if i'm doing it it a wrong way,what is the best approach??Thank you. 如果我做错了,最好的方法是什么?谢谢。

You're expecting a collection but you pass in an individual item to the view instead. 您期望有一个集合,但是您将单个项目传递给视图。

MvcApp.ViewModel.PlanObjectsViewModel = object System.Collections.Generic.IEnumerable[MvcApp.ViewModel.PlanObjectsViewModel] = collection of objects MvcApp.ViewModel.PlanObjectsViewModel =对象System.Collections.Generic.IEnumerable[MvcApp.ViewModel.PlanObjectsViewModel] =对象的集合

Change this 改变这个

@model IEnumerable<MvcApp.ViewModel.PlanObjectsViewModel>

to

@model MvcApp.ViewModel.PlanObjectsViewModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM