Search code examples
asp.net-mvcasp.net-coremodel-view-controllerrazorviewbag

Pass model to PartialAsync view (Razor, MVC)


I have AccountController.cs with below action:

[HttpGet]
[AllowAnonymous]
public IActionResult Register()
 {
   ViewBag.Registration = GetRegistration();
   return View();
 }

ViewBag.Registration contains 2 elements and it's ok.

Then I got Registration.cshtml view:

@model Registration <!-- this model I'm using for other form -->   
@{
    Layout = "_Layout";
}    
<!-- some code -->

@await Html.PartialAsync("AllRegistered")

and AllRegistered.cshtml where data from ViewBag.Registration should be displayed:

@model IEnumerable<Registration>

<table>
    <tr>
        <th>@Html.DisplayNameFor(m => m.Email)</th>
        <th>@Html.DisplayNameFor(m => m.City)</th>
    </tr>

    @if (Model != null && Model.Count() != 0)
    {
        @foreach (Registration registration in Model)
        {
            <tr>
                <th>@Html.DisplayFor(m => registration.Email)</th>
                <th>@Html.DisplayFor(m => registration.City)</th>
            </tr>
        }
     }
</table>

But nothing is generated into view, Model I think is empty.


Solution

  • The PartialAsync method contains an overload which includes the model:

    Html.PartialAsync(string partialViewName, TModel model)

    You should include the IEnumerable<Registration> (the partial view's model) in that helper.

    If GetRegistrations() is returning that IEnumerable, you would define the partial view like this:

    @await Html.PartialAsync("AllRegistered", (List<Registration>)ViewBag.Registration)