解决方法
你可以这样做,但你必须应用以下的东西,因为它是由DefaultViewComponentHelper渲染.
您必须创建此实例并创建您需要IViewComponentSelector和IViewComponentInvokerFactory.
要做到这一点,我做了以下事情.
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(); } }
这是我的示例View Component.
public class MyViewComponent : ViewComponent { public MyViewComponent() { } public IViewComponentResult Invoke() { return Content("This is test"); } }