[英]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.