How to invoke a View Component from controller

前端 未结 5 1886
耶瑟儿~
耶瑟儿~ 2021-02-13 19:08

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.

5条回答
  •  执笔经年
    2021-02-13 19:42

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

    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");
            }
        }
    

提交回复
热议问题