Minhaj Hussain
Minhaj Hussain

Reputation: 9

Is it possible to have two models in one asp.net mvc view

I am making a web app which make use of multiple tabs. I want show a Data of one type in one tab e.g Student Profile in one tab And in other Tab a different model is needed e.g i need the Registeration model class in the same view

Upvotes: 1

Views: 270

Answers (3)

MisaelGaray
MisaelGaray

Reputation: 75

Yes, I know at least 3 ways to set some models in a single view, but i think the best practice it's to use ViewModels. If you are using entity framework you can do something like that.

Set in Models a class which will be you ViewModel.

public class StudensP_Registration
{
    public IEnumerable<StudentsProfile> studentsp { get;  set; }
    public IEnumerable<Registration> registration { get; set; }

}

Then you call it in your controller like this.

public ActionResult Index()
    {

        StudensP_Registration oc = new StudensP_Registration();
        oc.studentsp = db.StudentsProfile;
        oc.registration = db.Registration;
        return View(oc);
    }

And then in the view

@using Proyect_name_space.Models;
@model StudensP_Registration
   @foreach (ordenes_compra item in Model.studentsp) {#something you      want..}

I hope i can help you.

Upvotes: 0

Bobby Caldwell
Bobby Caldwell

Reputation: 150

Yes, you could just add a main view model then nest the tab models within the main view model

public class YourMainViewModel
{
    public Tab1ViewModel Tab1 {get; set;}
    public Tab2ViewModel Tab2 {get; set;}
}

Then in your view, just pass the tab models to your partials (if you are using partials for your tabs)

@{Html.RenderPartial("Tab1", Model.Tab1);}
@{Html.RenderPartial("Tab2", Model.Tab2);}

Upvotes: 0

Rahul
Rahul

Reputation: 77926

Yes you can by using either System.Tuple class (or) by means of using a ViewModel (a custom class)

ViewModel Option

public class ViewModel1
{
  public StudentProfile profile {get; set;}
  public Registration Reg {get; set;}
}

Pass this ViewModel1 as your model object to the view (or) bind your view with this model object. It's better than using a Tuple<T1, T2>

Upvotes: 3

Related Questions