MVC 4 – 如何将模型数据传递到局部视图?

我正在构建一个配置文件页面,其中包含许多与特定模型(租户)相关的部分 – AboutMe,MyPreferences – 这些事情。 这些部分中的每一部分都将是部分视图,以允许使用AJAX进行部分页面更新。

当我点击TenantController中的ActionResult时,我能够创建一个强类型视图,并将模型数据传递给视图。 部分观点无法实现这一点。

我创建了一个局部视图_TenantDetailsPartial

 @model LetLord.Models.Tenant 
@Html.LabelFor(x => x.UserName) // this displays UserName when not in IF @Html.DisplayFor(x => x.UserName) // this displays nothing

然后我有一个视图MyProfile将呈现提到的部分视图:

 @model LetLord.Models.Tenant 
@Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", new ViewDataDictionary())

如果我在@if(model != null){}内的@if(model != null){}中将代码包装在DIV中,那么页面上就不会显示任何内容,所以我猜测有一个空模型被传递给视图。

为什么当我从ActionResult创建一个强类型视图时,’session’中的用户被传递给视图? 如何将’session’中的用户传递给不是从ActionResult创建的局部视图? 如果我对这个概念遗漏了一些,请解释一下。

您实际上并没有将模型传递给Partial,而是传递了一个new ViewDataDictionary() 。 试试这个:

 @model LetLord.Models.Tenant 
@Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)

此外,这可以使它工作:

 @{ Html.RenderPartial("your view", your_model, ViewData); } 

要么

 @{ Html.RenderPartial("your view", your_model); } 

有关RenderPartial和MVC中类似HTML帮助程序的更多信息,请参阅这个流行的StackOverflow线程

将模型数据传递给局部视图的三种方法(可能还有更多)

这是视图页面

方法一在视图中填充

 @{ PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel(); ctry1.CountryName="India"; ctry1.ID=1; PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel(); ctry2.CountryName="Africa"; ctry2.ID=2; List CountryList = new List(); CountryList.Add(ctry1); CountryList.Add(ctry2); } @{ Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList ); } 

方法二通过ViewBag

 @{ var country = (List)ViewBag.CountryList; Html.RenderPartial("~/Views/PartialViewTest.cshtml",country ); } 

方法三通过模型

 @{ Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country ); } 

在此处输入图像描述