0

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.

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

The 2nd part worked for me. Its so simple & I'm so stupid for didn't try hard enough. Tnx. :)
3

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

Comments

0

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.

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.