2017-08-13 110 views
0

問題是我需要在School視圖中「調用」PersonName字段,但視圖School中的模型是@model IList<Project.Presentation.Models.SchoolViewModel>,並且字段PersonName在型號爲@model IList<Project.Presentation.Models.PersonViewModel>所以,我想我必須在同一視圖中使用兩個模型,但我不知道該怎麼做。我不知道我是否只能使用一個代碼行來「調用」我需要的字段,或者如果我必須執行某些操作。ASP.NET MVC-在同一視圖中使用兩個模型

這裏是在視圖中學校代碼:

@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> 
} 

我與@Html.DisplayFor(Project.Presentation.Models.PersonViewModel.PersonName)努力,但顯然它不工作。

+2

創建包含屬性您需要的視圖模型 –

回答

1

您的視圖模型將包括你需要在一個視圖中的所有財產 - 因此PersonViewModel應該是財產的視圖模型

你沒有出示名字SchoolViewModelPersonViewModel

但法官之間的關係,我猜測這是一個一對多的關係 - 即一個SchoolViewModel會有很多PersonViewModel代表在學校的人

這樣的基礎上的假設,你SchoolViewModel可能看起來像這樣的:

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

那麼在您看來,它看起來像:

@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> 
} 

所以關鍵是,把你所有需要的屬性,你的視圖模型

0

創建一個視圖模型和包含此在那裏

public class SchoolPersonViewModel 
{ 

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

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

} 

在查看

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

PersonList是列表,所以使用的foreach

同樣喜歡SchoolList

相關問題