How to Pass Multiple ViewData.Models to View in C#MVC4

Asked 1 years ago, Updated 1 years ago, 79 views

If I use multiple models to view the view, how do I pass it over?

public ActionResult Index()
    {

        using(var context=new testDBEntities())
        {
            // First Model
            ViewData.Model=(from u in context.test1data)
                              orderby u.startTime ascending
                              select u).Take(5).ToList();
        }

        using(var context=new testDBEntities())
        {
            // Second Model
            ViewData.Model=(from u in context.test2data)
                              orderby u.startTime ascending
                              select u).Take(5).ToList();
        }

        return View();
    }

index.cshtml

// Display the first model in a loop
@foreach(vars in ViewData.Model)
{
@s.itemName
}
// Display the second model in a loop
@foreach(vars in ViewData.Model)
{
@s.itemName2
}

c# .net asp.net

2022-09-30 19:39

1 Answers

The model should be the type that holds the two models.

//Assume the variable model1,model2;

using(var context=new testDBEntities())
{
    // First Model
    model1=(from u in context.test1data)
                      orderby u.startTime ascending
                      select u).Take(5).ToList();
}

using(var context=new testDBEntities())
{
    // Second Model
    model2=(from u in context.test2data)
                      orderby u.startTime ascending
                      select u).Take(5).ToList();
}

ViewData.Model=new{Model1=model1,Model2=model2};

return View();


2022-09-30 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.