2

我正在尝试将两个模型传递给局部视图。问题是在我的视图中我只能找到:“Model.Class1”和“Model.Class2”,而我实际上想要获取 Model.Class2.UserID ..

我确实让它工作了,但后来它抱怨 GetEnumerator() 什么的。还尝试了元组,这对我来说根本不起作用。对 ASP NET MVC 来说非常新,所以我很菜鸟!:) 请回复!

型号类:

   public class Class1ANDClass2
    {
        public IEnumerable<Klubben.Models.Class1> class1 { get; set; }
        public IEnumerable<Klubben.Models.Class2> class22{ get; set; }
    }

我的观点:

   @model IEnumerable<Klubben.Models.Class1ANDClass2>////(Contains classes Omraade and Medlem)

   @foreach (var item in Model)
   {
    if(item.Class1.UserID >= 1)  ////This does not work, which i need it to do
       ///For example show item.Class2.Username

    }

我的控制器:

public ActionResult PartialView()
        {
            try
            {
                IEnumerable<Class1> c1 = some object
                IEnumerable<Class2> c2 = some object

                Class1ANDClass2 omt= new Class1ANDClass2();
                omt.Class1 = c1
                omt.Class2 = c2;

                return PartialView("MyPartial", omt);
            }
            catch (Exception feil)
            {
                return PartialView("exception");
            }
        }
4

3 回答 3

3

问题出在你的循环上

@model IEnumerable<Klubben.Models.Class1ANDClass2>////(Contains classes Omraade and Medlem)

@foreach (var item in Model.class1)
{
 if(item.UserID >= 1)  ////This does not work, which i need it to do
    ///For example show item.Username

}

// similarly for class2

@foreach (var item in Model.class2)
{
  if(item.aProperty >= 1)  ////This does not work, which i need it to do
    ///For example show item.otherProperty

}
于 2013-04-21T19:46:46.797 回答
0

您正在从您的操作方法返回一个名为 omt 的对象。但是您的观点期待 IEnumerable 。

将视图模型声明更改为

**@model Klubben.Models.Class1ANDClass2**

@foreach (var item in Model.Class1)
{
if(item.Class1.UserID >= 1)  ////This does not work, which i need it to do
   ///For example show item.Class2.Username
}
于 2013-04-22T17:15:48.937 回答
0

您可以使用Tuple视图中访问多个模型,如下所示:

@model Tuple<FirstModel, SecondModel>

<div> 
    @Model.Item1.FirstModelProp
    @Model.Item2.SecondModelProp
</div>
于 2016-08-12T04:38:23.960 回答