简体   繁体   中英

How to render partial view inside a view in ASP.NET MVC

I'm fairly new to ASP.NET MVC. I have to render Partial View inside a View. My Partial view has a model and an action method MangeUsersInRole . Anyways, I tried Html.RenderPartial, Html.Partial. One webpage, I'm experiencing an exception:

例外

Heres my approach: View:

@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");

Partial View:

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

The partial view model uses whichever model type was used in its parent view in this case UserRole instead of List<ManageUsersInRole> unless you explicitly pass the model value as parameter with the expected type you explicitly express in the partial view in this case List<ManageUsersInRole> One approach to handle multiple model types for a single view or single + partial view is to create a view model with fields of each of the different model types you need and then pass them to partials as you need. For example:

public class UserViewModel
{
   public UserRole Role { get; set; }

   public List<ManageUsersInRole> UsersInRole { get; set; }

}

Then in your parent view you reference the UserViewModel and pass UsersInRole to the partial view. Example:

@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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM