Mat*_*ull 32 c# asp.net-mvc model partial-views asp.net-mvc-views
我正在构建一个配置文件页面,其中包含许多与特定模型(租户)相关的部分 - AboutMe,MyPreferences - 这些事情.这些部分中的每一部分都将是部分视图,以允许使用AJAX进行部分页面更新.
当我点击ActionResultTenantController中的一个时,我能够创建一个强类型视图,并将模型数据传递给视图.部分观点无法实现这一点.
我创建了一个局部视图_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>
Run Code Online (Sandbox Code Playgroud)
然后我有一个视图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>
Run Code Online (Sandbox Code Playgroud)
如果我将代码包装在DIV _TenantDetailsPartial里面@if(model != null){},那么页面上就不会显示任何内容,所以我猜测有一个空模型被传递给视图.
为什么我ActionResult在'session'中创建一个来自用户的强类型视图会被传递给视图?如何将'session'中的用户传递给不是从ActionResult?创建的局部视图?如果我遗漏了这个概念,请解释一下.
Dan*_*mms 63
你实际上并没有将模型传递给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>
Run Code Online (Sandbox Code Playgroud)
Irs*_*shu 14
我知道问题是 MVC4 特有的。但由于我们已经过了 MVC4,如果有人正在寻找ASP.NET Core,您可以使用:
<partial name="_My_Partial" model="Model.MyInfo" />
Run Code Online (Sandbox Code Playgroud)
lzl*_*yle 13
此外,这可以使它工作:
@{
Html.RenderPartial("your view", your_model, ViewData);
}
Run Code Online (Sandbox Code Playgroud)
要么
@{
Html.RenderPartial("your view", your_model);
}
Run Code Online (Sandbox Code Playgroud)
有关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<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Run Code Online (Sandbox Code Playgroud)
方法二 通过ViewBag
@{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Run Code Online (Sandbox Code Playgroud)
方法三 通过模型
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97534 次 |
| 最近记录: |