2

I am trying to pass two models in to a partial view. Problem is that in my View i can only find : "Model.Class1" and "Model.Class2",while i actually want to get Model.Class2.UserID..

I did get it to work but then it complained about GetEnumerator() or something. Also tried tuple, which didnt work at all for me. Very new to ASP NET MVC so im rlly noob! :) Please reply!

Model class:

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

My view:

   @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

    }

My Controller:

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");
            }
        }

3 Answers 3

3

The problem is with your loop

@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

}
Sign up to request clarification or add additional context in comments.

Comments

0

You are returning a single object called omt from your action method. But your view is expecting an IEnumerable .

Change the view model declaration to

**@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
}

Comments

0

you can use Tuple to access multiple models in view as below:

@model Tuple<FirstModel, SecondModel>

<div> 
    @Model.Item1.FirstModelProp
    @Model.Item2.SecondModelProp
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.