ViewComponent返回,但使用路由值时视图中的模型为null

对于razorpages和viewcomponents仍然是新手,但是在asp.net上已经出现了好几次

不确定为什么我的viewcomponent没有填充其模型。 我注意到我做错了一件事,就是在顶部放置一个路由参数
例如。

sed

我知道(至少现在)不打算将ViewComponents直接作为端点路由,但是现在我很好奇,使用带有route属性的@page来防止模型绑定发生了什么?我只是通过反复试验才发现,删除它会使我的模型填充到ViewComponent中。

这是代码

ViewComponent

awk

View for ViewComponent, Default.html

@page "{handler?}"

CustomerListModel

public class TestViewComponent : ViewComponent
{

    public async Task<IViewComponentResult> InvokeAsync(Data.CustomerListModel cust)
    {
        List<Data.CustomerListModel> clist = new List<Data.CustomerListModel>();
        clist.Add(new Data.CustomerListModel() { Customer = "fred" });
        clist.Add(new Data.CustomerListModel() { Customer = "wilma" });

        var dlist = clist.AsEnumerable();

        return View(dlist);
    }
}

父视图, Index.cshtml

@page "{handler?}"
@using System.Collections.Generic
@addTagHelper *,TelerikAspnetCoreApp1
@model IEnumerable<Data.CustomerListModel>

<h1>Default</h1>

<h3>Machine name @Environment.MachineName</h3>
<ul>
    @foreach (Data.CustomerListModel c in Model)
    {
        <li>@c.Customer</li>
    }
</ul>
atx860 回答:ViewComponent返回,但使用路由值时视图中的模型为null

ViewComponent的视图非常类似于ASP.NET Core应用程序中带有控制器和视图的Razor视图文件。然后,在Razor页面中使用@page伪指令,它使文件成为MVC操作-这意味着它无需通过控制器即可直接处理请求。 @page影响其他Razor构造的行为。

您可以花些时间阅读View Component和Razor Pages上的MS文档:

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-3.0

https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.0&tabs=visual-studio

本文链接:https://www.f2er.com/3151567.html

大家都在问