Shihan Khan
Shihan Khan

Reputation: 2188

Two models in same view in asp.net mvc

I'm new to asp.net & I'm trying to make a website with asp.net mvc 4 & EF6 where I need two models to work under the same view. I've tried a lot but couldn't figure out how to make that work. Here are my codes,

Controller

public ActionResult AfterLogin()
    {
        if (Session["UserNAME"] != null)
        {
            var firstmodel = new MyViewModel { stats = db.stats.ToList() };
            var secondmodel = new MyViewModel { mans = db.mans.ToList() };
            return View(firstmodel);   //How can I also add the "secondmodel"?
        }
        else
        {
            return RedirectToAction("Login");
        }
    }

Model

public class MyViewModel
{
    public IEnumerable<stat> stats { get; set; }
    public IEnumerable<man> mans { get; set; }
}

How can I use both model at the same time? Need this help badly. Tnx.

Upvotes: 0

Views: 147

Answers (3)

Slappywag
Slappywag

Reputation: 1223

Brandon and Jamiec's answers are definitely better for this situation, but if you really don't want to change the model, or create a new class then you can always add data to the ViewBag. In your Controller method:

 ViewBag.SecondModel = new MyViewModel { mans = db.mans.ToList() };

then in the view you can call it like:

@{
   MyViewModel secondModel = (MyViewModel) ViewBag.SecondModel;
 }

Note that you need to use the cast because anything in the ViewBag is dynamically typed.

Upvotes: 0

Brandon
Brandon

Reputation: 69983

You can only bind to one model.

Either create a new model that contains both of the models you want to use.

public class AfterLoginModel
{
    public MyViewModel Stats { get; set; }

    public MyViewModel Mans { get; set; }
}

or in your case, since they are the exact same model, you could also set both the stats and mans properties and pass in a single MyViewModel.

var model = new MyViewModel { 
                               stats = db.stats.ToList(),
                               mans = db.mans.ToList()
                            };
return View(model);

Upvotes: 3

Jamiec
Jamiec

Reputation: 136104

Make a model that contains both

public class CombinedModel
{
    public MyVieModel Model1 {get;set;}
    public MyVieModel Model2 {get;set;}
}

Use that for the view

public ActionResult AfterLogin()
{
    if (Session["UserNAME"] != null)
    {
        var firstmodel = new MyViewModel { stats = db.stats.ToList() };
        var secondmodel = new MyViewModel { mans = db.mans.ToList() };
        return View(new CombinedModel(){
           Model1 = firstmodel,
           Model2 = secondmodel
       });   //
    }
    else
    {
        return RedirectToAction("Login");
    }
}

Upvotes: 3

Related Questions