2013-03-01 164 views
24

我正在构建一个配置文件页面,其中会包含一些与特定模型(租户)相关的部分 - AboutMe,MyPreferences - 这些类型的东西。这些部分中的每一个都将成为局部视图,以允许使用AJAX进行局部页面更新。MVC 4 - 如何将模型数据传递给部分视图?

当我在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'中的用户传递给了视图,怎么会这样?如何在'会话'中将用户传递给不是从ActionResult创建的部分视图?如果我错过了这个概念,请解释一下。

回答

53

实际上并没有将模型传递给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> 
+4

我真的试过了更早,它没有工作!我不能重建我的解决方案......谢谢,它的工作原理。 – MattSull 2013-03-01 00:28:02

10

而且,这样可以使它的工作原理:

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

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

有关的RenderPartial和MVC类似HTML佣工更多信息,请参阅this popular StackOverflow thread

4

将模型数据传递到局部视图的三种方法(可能有m个矿)

这是视图页面

方法一填充在视图

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

+0

你可以请把部分视图代码以及。我没有得到任何东西,当使用第二种方法来传递值的局部视图 – 2017-04-07 13:19:45

+0

@HeemanshuBhalla我认为var countries = ViewBag.CountryList为List 可以给你的值 – 2017-04-07 14:52:30

相关问题