Home How to load partial razor page into razor view

# How to load partial razor page into razor view

user10038
1#
user10038 Published in September 19, 2018, 3:35 am

I am trying to replace my view components with razor pages but it seems that it's not possible to load a partial razor page because a model is expected to be passed yet it is my understanding that the model for a razor page should be declared in the OnGetAsync method. Here is my code...

Razor Page

@page "{id:int}"
@model _BackgroundModel

<form method="POST">
<div>Name: <input asp-for="Description" /></div>
<input type="submit" />
</form>


Razor Page Code-Behind

public class _BackgroundModel : PageModel
{

public _BackgroundModel(IDataClient dataClient)
{
_dataClient = dataClient;
}

[BindProperty]
public BackgroundDataModel Background { get; set; }

{
Background = await _dataClient.GetBackground(id);
}

{
if (ModelState.IsValid)
{
await _dataClient.PostBackground(Background);
}
}

}


Razor View

<div class="tab-pane fade" id="client-background-tab">
<div class="row">
<div class="col-sm-12">
@await Html.PartialAsync("/Pages/Client/_Background.cshtml", new { id = 1 })
</div>
</div>
</div>


InvalidOperationException: The model item passed into the ViewDataDictionary is of type '<>f__AnonymousType01[System.Int32]', but this ViewDataDictionary instance requires a model item of type 'WebApp.Pages.Client._BackgroundModel'

In this example (as per MS recommended approach in their docs) the model is set inside the OnGetAsync method which should be run when the page is requested. I have also tried @await Html.RenderPartialAsync("/Pages/Client/_Background.cshtml", new { id = 1 }) but the same error result.

How can I load the razor page into my existing view?

• You view model is _BackgroundModel  but you are calling the view with an int value. Try some thing like @await Html.PartialAsync("/Pages/Client/_Background.cshtml", new _BackgroundModel ()). – Ibrahim Khan Nov 12 '17 at 6:02
• @Azim The model should be created within the OnGetAsync within the code-behind file not passed by the calling view. The page load requires an int value as defined at the top of the razor page @page "{id:int}" and this int value is passed to OnGetAsync(int id) when page loads which is why i'm passing an int value from the calling view and not a model. – OjM Nov 12 '17 at 12:35
• if you are passing model to partial view then why you need to pass 'id' to it – Saineshwar Nov 13 '17 at 4:37
• @Saineshwar this is how razor pages work. They essentially have their own controller in the code-behind file and therefore do not need or expect a model to be passed. this is the same concept as view components which are called with @await Component.InvokeAsync("name")`. i was looking for a way to load a razor page in a similar way but it doesn't seem this is possible as per reply in the comments of MS docs Razor Pages – OjM Nov 13 '17 at 7:29