Ariel
Ariel

Reputation: 916

Get View outside Controller Context

Is there any way to get the view of a Controller from another Controller ?

For example i have my HelperController with several methods for the whole project and i have the function MontaCursosWall that is called on CursosController and this function needs to read a View that belongs to CursosController.

In another case i need this same function (MontaCursosWall) that is called from a function inside HelperController to read the same View.

I already have a code to read it but it's not working:

public string ToHtml(string pView, ControllerContext context)
{
    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(context, pView);
        var viewContext = new ViewContext(context, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(context, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

This is how i call it from the MontaCursosWall:

ToHtml(fileName, context).Split('|');

Where fileName is my View Name and context comes from the CursoController

Upvotes: 4

Views: 2375

Answers (1)

Ariel
Ariel

Reputation: 916

I managed to make it work after i deleted and re-created my views, it seems that my views weren't being recognized.

I'm gonna leave my code here if anyone else have the same problem.

public string ToHtml(string pView, ControllerContext context = null)
{
    if (context == null)
        context = ControllerContext;

    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(context, pView);
        var viewContext = new ViewContext(context, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(context, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

Upvotes: 4

Related Questions