簡體   English   中英

如何在 ASP.NET MVC 中的視圖內呈現局部視圖

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM