1

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
{
    private readonly IDataClient _dataClient;

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

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

    public async Task OnGetAsync(int id)
    {
        Background = await _dataClient.GetBackground(id);
    }

    public async Task OnPostAsync()
    {
        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>

Page Load Error

InvalidOperationException: The model item passed into the ViewDataDictionary is of type '<>f__AnonymousType0`1[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?

4

1 回答 1

1

Microsoft 确认这无法实现,因此剃刀页面不能用作视图组件的替代品。

查看他们文档的评论...

微软文档

@RickAndMSFT 版主 15 小时前 @OjM 您可以重定向到页面,或者您可以将核心视图 > 代码变为部分代码并从两者中调用它。

页面不能替代部分或视图组件。

于 2017-11-13T21:48:31.123 回答