从另一个控制器查看到字符串 [英] View to String from another controller
问题描述
我已经按照Vdex的建议完成了:
https://stackoverflow.com/a/5801502/973485
并使用了他发现的RenderPartialToString
方法.它像这样完美地工作:
i have done as Vdex suggested here:
https://stackoverflow.com/a/5801502/973485
And used the RenderPartialToString
method he found. And it works perfectly like this:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Test()
{
string t = ViewToString.RenderPartialToString("Index", null, ControllerContext);
return Content(t);
}
}
但是,如果我想从另一个Controller渲染Home> Index,我会得到:
But if i want to render the Home > Index from another Controller, i get:
Value cannot be null.
Parameter name: controllerContext
赞:
public class FooController : Controller
{
public ActionResult Index()
{
string t = ViewToString.RenderPartialToString("Index", null, new HomeController().ControllerContext);
return Content(t);
}
}
有什么方法可以将View从另一个Controller传递给字符串吗?我尝试了许多不同的方法,但所有这些方法在ControllerContext上都失败了.非常感谢!
Is there any way to pass a View from another Controller to a string? I have tried many different methods, and it all of them fails at the ControllerContext. Many thanks!
更新:为什么我需要这样做:
想象一下,我的网站充满了小部件,每个页面上的小部件数量是动态的,因此我无法将其硬编码到我的cshtml文件中.但是在该文件中,定义了不同的区域,在这些区域中小部件被打印输出.要打印出这些小部件,我有一个IWidgetController列表,其中包含所有可用的小部件,并且接口表示它们需要包含ActionResult才能进行编辑,新建和查看.小部件示例:CalenderController,NewsController,GalleryController等...因此,在这些区域中,我需要打印出每个Controller的内容.现在我还可以加载URLHTML,但是我认为从内部执行操作会更快...对吧?
Imagine i have a website full of widgets, the amount of widgets on each page is dynamic, so i cannot hardcode them in my cshtml file. But in that file there are different areas defined where the widgets gets printet out. To print out these widget i have a list of IWidgetController wich contains alle the different Widgets available, and the interface sais that they need to containe a ActionResult for edit, new and view. example of widgets: CalenderController, NewsController, GalleryController and so on... So in those areas i need to print out the content of each of those Controllers. Now i could also load the URLHTML but i figured doing it from the inside would be faster... right?
推荐答案
尝试一下:
string t = ViewToString.RenderPartialToString("Index", null, this.ControllerContext);
无论如何,为什么需要转换为字符串?
Anyway, why do you need to convert to a string?
这篇关于从另一个控制器查看到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!