ASP.NET MVC - Use two models in the same view

286 views Asked by At

The problem is that I need to "call" the PersonName field in the view of School, but the model in the view School is @model IList<Project.Presentation.Models.SchoolViewModel>, and the field PersonName is in the model @model IList<Project.Presentation.Models.PersonViewModel>. So, I guess I have to use two models in the same view, but I don't know how to do it. I don't know if I can only "call" the field I need using just one code line or if I have to do something behind.

Here is the code in the view School:

@model IList<Project.Presentation.Models.SchoolViewModel>

@{
ViewBag.Title = "Start view";
}@
{            
        <div class="row">
            <div class="col-md-6 ">                    
                <h2>
                    Details of the person @Html.DisplayFor(Project.Presentation.Models.PersonViewModel.PersonName)
                </h2>                   
            </div>
        </div>
}

I'm trying with@Html.DisplayFor(Project.Presentation.Models.PersonViewModel.PersonName), but obviously it doesn't works.

2

There are 2 answers

0
Alan Tsai On

your viewmodel will include all the property you will need in a view - so PersonViewModel should be a property in your viewmodel

you did not show the relationship between SchoolViewModel and PersonViewModel

but judge by the name, I am guessing it is a one to many relationship - i.e one SchoolViewModel will have many PersonViewModel representing the person in school

so base on that assumption, your SchoolViewModel may look like this:

public class SchoolViewModel
{
    // other property ..
    public IList<Project.Presentation.Models.PersonViewModel> PersonList {get; set;}
}

then in your view, it will look like:

@model IList<Project.Presentation.Models.SchoolViewModel>

@// first loop school
@for(int i =0; i < Model.Count; i++)
{
    <div class="row">
        @// then loop all person in the school
        @for(int j = 0; j < Model[i].PersonList.Count; j++)
        {
            <div class="col-md-6 ">                    
                <h2>
                    Details of the person @Html.DisplayFor(modelItem => Model[i].PersonList[j].PersonName )
                </h2>                   
            </div>
        }
    </div>
}

so the key is, put all your needed property to your viewmodel

0
Abdulla Sirajudeen On

Create a View Model and Include this Two Model in there

public class SchoolPersonViewModel
{

public IList<Project.Presentation.Models.PersonViewModel> PersonList {get; set;}

public IList<Project.Presentation.Models.SchoolViewModel> SchoolList {get; set;}

}

In View

            <div class="row">
            <div class="col-md-6 ">                    
                <h2>
                    Details of the person 
    @Html.DisplayFor(model => model.PersonList)
                </h2>                   
            </div>
        </div>

PersonList is List, So Use foreach

Same Like SchoolList