[英]How to render partial view inside a view in ASP.NET MVC
我对 ASP.NET MVC 相当陌生。 我必须在视图中呈现局部视图。 我的 Partial 视图有一个模型和一个操作方法MangeUsersInRole 。 无论如何,我尝试了 Html.RenderPartial、Html.Partial。 一个网页,我遇到了一个例外:
这是我的方法:查看:
@model UserRole
<form method="post" action="/HKRole/AddUserToRole">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="@Model.Id" name="roleId" class="form-control" hidden />
</div>
</form>
@Html.Partial("ManageUsersInRole");
部分视图:
@model List<ManageUsersInRole>
<table class="table">
<thead>
<tr>
<th>User Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
@for (int i = 0; i < Model.Count; i++)
{
<td>@Model[i].UserName</td>
<td>@Model[i].UserEmail</td>
}
</tr>
</tbody>
</table>
在这种情况下, List<ManageUsersInRole>
视图model
使用在其父视图中使用的任何模型类型UserRole
而不是List<ManageUsersInRole>
除非您显式地将模型值作为参数传递给您在List<ManageUsersInRole>
视图中明确表达的预期类型在这种情况下List<ManageUsersInRole>
处理单个视图或单个 + 局部视图的多种模型类型的一种方法是创建一个视图模型,其中包含您需要的每种不同模型类型的字段,然后根据需要将它们传递给局部视图。 例如:
public class UserViewModel
{
public UserRole Role { get; set; }
public List<ManageUsersInRole> UsersInRole { get; set; }
}
然后在您的父视图中引用UserViewModel
并将UsersInRole
传递给局部视图。 例子:
@model UserViewModel
<form method="post" action="/HKRole/AddUserToRole">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="@Model.Role.Id" name="roleId" class="form-control" hidden />
</div>
</form>
@Html.Partial("ManageUsersInRole", Model.UsersInRole);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.