c# - 从另一个 Controller 查看到字符串

标签 c# asp.net-mvc asp.net-mvc-3 razor

我已经按照 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/

相关文章:

asp.net - ASP.NET MVC 3 应用程序中每个浏览器选项卡/窗口的新 session

asp.net-mvc - 如何在 mvc4 razor 的文本框中仅允许数字

asp.net-mvc-3 - 如何在输出缓存中使用动态持续时间值?

c# - 在 C# 中等待 C++ 中的事件 - 作为任务或等待句柄

c# - TextBlock 绑定(bind)不起作用

c# - 在循环中填充快捷键

c# - 从 C# 应用程序中添加 reg 并从 cmd 窗口中查询值后出现不同值的原因是什么?

asp.net-mvc - 如何让 RoleProvider 工作?

javascript - flow.js 点击上传文件

asp.net - 有 www 和无 www 的表单例份验证