【问题标题】:Get rendered result of View Component in derived RazorPage在派生的 RazorPage 中获取视图组件的渲染结果
【发布时间】:2017-04-27 19:40:55
【问题描述】:

我需要从派生的RazorPage 中获取视图组件的渲染结果。在 .cshtml 文件中,我可以做

@await Component.InvokeAsync("MyButton", new MyModel())

现在,如果我的剃须刀页面继承自这个类:

public class MyRazorPage<TModel> : RazorPage<TModel>
{
    public async Task<HtmlString> GetViewComponentForExample()
    {
        // I cannot access the injected "Component" this way...
        string temp = await Component.InvokeAsync("MyButton", new MyModel()).Result.WriteTo();
        return new HtmlString(temp);
    }
}

在上面的方法GetViewComponentForExample()我不能使用注入的Component属性。如何访问 Component 属性,或者如何完成上述操作?

【问题讨论】:

    标签: c# razor asp.net-core-viewcomponent


    【解决方案1】:

    你能做的就是这个(ASP .Net Core 2.0)

    如果你有这样的组件:

    [ViewComponent(Name = "Cart")]
    public class CartViewComponent : ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync()
        {
             return View("");
        }
    }
    

    你可以像这样在控制器中调用它

    public class OtherController : Controller
    {
        [HttpGet]
        public IActionResult Cart()
        {
            return ViewComponent("Cart");
        }
    }
    

    这会返回一个渲染的组件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2017-01-31
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多