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

43
我正在构建一个个人资料页面,其中包含与特定模型(租户)相关的多个部分 - 关于我、我的偏好等。每个部分都将是一个局部视图,以允许使用 AJAX 进行局部页面更新。
当我在 TenantController 中单击一个 ActionResult 时,我能够创建一个强类型视图,并将模型数据传递给视图。但是我无法通过局部视图实现这一点。
我已经创建了一个局部视图 _TenantDetailsPartial:
@model LetLord.Models.Tenant
<div class="row-fluid">
    @Html.LabelFor(x => x.UserName) // this displays UserName when not in IF
    @Html.DisplayFor(x => x.UserName) // this displays nothing
</div>

我随后有一个视图MyProfile,用于呈现上述的局部视图:
@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", 
         new ViewDataDictionary<LetLord.Models.Tenant>())
    </div>
</div>

如果我将 _TenantDetailsPartial DIV 内的代码放在 @if(model != null){} 中,页面上什么都不会显示,所以我猜测一个空模型被传递给了视图。
当我从 ActionResult 创建强类型视图时,为什么'Session'中的用户会被传递到视图中?如何将'Session'中的用户传递给不是从 ActionResult 创建的部分视图?如果我对概念有所遗漏,请解释一下。
4个回答

78

您实际上并没有将模型传递给Partial,而是传递了一个new ViewDataDictionary<LetLord.Models.Tenant>()。请尝试以下方法:

@model LetLord.Models.Tenant
<div class="row-fluid">
    <div class="span4 well-border">
         @Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
    </div>
</div>

5
我之前真的尝试过那个方法,但它并没有起作用!我一定是没有重新构建我的解决方案……谢谢,现在它有效了。 - MattSull

15

此外,这可能使其正常工作:

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

了解更多有关MVC中RenderPartial和类似HTML助手的信息,请参阅这个受欢迎的StackOverflow帖子


14

我知道问题是特定于MVC4的。但是由于我们已经超出了MVC4,如果有人寻找ASP.NET Core,您可以使用:

<partial name="_My_Partial" model="Model.MyInfo" />

7

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

这是视图页面

第一种方法 在视图中填充

@{    
    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<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

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

第二种方法 通过 ViewBag 传递数据

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

第三种方法:经过模型处理

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

enter image description here


1
请问您能否同时提供一下Partial View的代码?当我使用第二种方法传递值到Partial View时,什么也没有显示出来。 - Heemanshu Bhalla
@HeemanshuBhalla 我认为 var countries = ViewBag.CountryList as List<PartialViewTestSOl.Models.CountryModel> 可以给你赋值。 - Arun Prasad E S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接