View to String from another controller

2019-05-23 03:34发布

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

But if i want to render the Home > Index from another Controller, i get:

Value cannot be null.
Parameter name: controllerContext

Like this:

public class FooController : Controller
{
    public ActionResult Index()
    {
        string t = ViewToString.RenderPartialToString("Index", null, new HomeController().ControllerContext);
        return Content(t);
    }
}

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!

Update: Why i need to do this:

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?

1条回答
男人必须洒脱
2楼-- · 2019-05-23 04:35

Try this:

string t = ViewToString.RenderPartialToString("Index", null, this.ControllerContext);

Anyway, why do you need to convert to a string?

查看更多
登录 后发表回答