如何从控制器调用视图组件 [英] How to invoke a View Component from controller

查看:96
本文介绍了如何从控制器调用视图组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从控制器调用View组件并将其呈现为字符串?我真的在为此寻找一些代码示例.任何帮助将不胜感激.

Is it possible to invoke a View Component from controller and render it to a string? I am really looking for some code example for this. Any help will be much appreciated.

推荐答案

您可以执行此操作,但是必须应用以下内容,因为它是由DefaultViewComponentHelper呈现的.

You can do that but you have to apply following thing as It is render by DefaultViewComponentHelper.

您必须创建此实例并创建所需的IViewComponentSelector和IViewComponentInvokerFactory.

You have to create instance of this and to create that you need IViewComponentSelector and IViewComponentInvokerFactory.

为此,我做了以下事情.

To do this I have done following thing.

public class HomeController : Controller
    {
        Microsoft.AspNet.Mvc.DefaultViewComponentHelper helper = null;
        Microsoft.AspNet.Mvc.Razor.RazorView razorView = null;
        public HomeController(IViewComponentSelector selector,IViewComponentInvokerFactory factory,IRazorPageFactory razorPageFactory,IRazorPageActivator pageActivator,IViewStartProvider viewStartProvider)
        {
            helper = new DefaultViewComponentHelper(selector, factory);
            razorView = new Microsoft.AspNet.Mvc.Razor.RazorView(razorPageFactory, pageActivator, viewStartProvider);           
        }
        public IActionResult Index()
        {                  
            ViewContext context = new ViewContext(ActionContext, razorView, ViewData, null);
            helper.Contextualize(context);
            string st1 = helper.Invoke("My", null).ToString();
            return View();
        }
}

这是我的示例视图组件.

Here is my sample View Component.

 public class MyViewComponent : ViewComponent
    {     

        public MyViewComponent()
        {

        }

        public IViewComponentResult Invoke()
        {
            return Content("This is test");
        }
    }

这篇关于如何从控制器调用视图组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆