如何将部分剃刀页面加载到剃刀视图中 [英] How to load partial razor page into razor view
问题描述
我正在尝试用剃刀页面替换视图组件,但是似乎无法加载部分剃刀页面,因为期望传递模型,但据我了解,应该声明剃刀页面的模型在OnGetAsync方法中.这是我的代码...
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...
剃刀页
@page "{id:int}"
@model _BackgroundModel
<form method="POST">
<div>Name: <input asp-for="Description" /></div>
<input type="submit" />
</form>
剃刀页面代码隐藏
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);
}
}
}
剃刀视图
<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:模型项传递到 ViewDataDictionary的类型为'<> f__AnonymousType0`1 [System.Int32]', 但是此ViewDataDictionary实例需要一个类型为的模型项 'WebApp.Pages.Client._BackgroundModel'
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'
在此示例中(按照MS在其文档中推荐的方法),该模型是在OnGetAsync方法中设置的,应在请求页面时运行该方法.我还尝试了@await Html.RenderPartialAsync("/Pages/Client/_Background.cshtml",新的{id = 1}),但结果相同.
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.
如何将剃须刀页面加载到现有视图中?
推荐答案
Microsoft确认无法实现此功能,因此剃刀页面不能用作视图组件的替代品.
Microsoft confirmed this cannot be achieved and therefore razor pages cannot be used as a replacement for view components.
查看他们文档的评论...
See the comments of their docs...
@RickAndMSFT主持人15小时前 @OjM您可以重定向到页面,也可以将核心视图>代码部分化,然后从两者中调用它.
@RickAndMSFT moderator15 hours ago @OjM You can redirect to the page, or you can make the core view >code into a partial and call it from both.
页面不能代替局部或视图组件.
Pages are not a replacement for partials or View Components.
这篇关于如何将部分剃刀页面加载到剃刀视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!