我已经按照 Vdex 的建议做了:
https://stackoverflow.com/a/5801502/973485
并使用了他找到的 RenderPartialToString
方法。它像这样完美地工作:
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,我会得到:
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 上失败了。非常感谢!
更新:为什么我需要这样做:
假设我有一个充满小部件的网站,每个页面上的小部件数量是动态的,所以我不能在我的 cshtml 文件中对它们进行硬编码。但是在那个文件中,有不同的区域定义了小部件打印出来的地方。为了打印出这些小部件,我有一个 IWidgetController 列表,其中包含所有可用的不同小部件,并且界面说它们需要包含一个 ActionResult 以进行编辑、新建和查看。小部件的示例:CalenderController、NewsController、GalleryController 等等...所以在这些区域我需要打印出每个 Controller 的内容。现在我也可以加载 URLHTML 但我认为从内部加载会更快......对吧?
最佳答案
试试这个:
string t = ViewToString.RenderPartialToString("Index", null, this.ControllerContext);
不管怎样,为什么需要转换成字符串?
关于c# - 从另一个 Controller 查看到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8606752/