tags:

views:

100

answers:

1

Hi

I have a method

RenderToString(string pathToView, string pathToMasterPage)

which, like the name already says, renders a view and returns the result as a string. Currently I have to pass the path to the master page as a paramter to the method. But since the view itself allready contains the definition of the master page

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

I was wondering if it is possible to read this value programaticly, so that I don't have to pass it as a seperate parameter anymore?

+1  A: 

Hi

The RenderToString method looks like this:

public virtual string RenderToString(string viewPath, string masterPath)
{
    ControllerContext controllerContext = this.ControllerContext;
    Stream filter = null;
    ViewPage viewPage = new ViewPage();

    viewPage.ViewContext = new ViewContext(this.ControllerContext, new WebFormView(viewPath, masterPath), this.ViewData, this.TempData);

    //get the response context, flush it and get the response filter.
    var response = viewPage.ViewContext.HttpContext.Response;
    response.Flush();
    var oldFilter = response.Filter;

    try
    {
        //put a new filter into the response
        filter = new MemoryStream();
        response.Filter = filter;

        //render the view into the memorystream and flush the response
        viewPage.ViewContext.View.Render(viewPage.ViewContext, viewPage.ViewContext.HttpContext.Response.Output);
        response.Flush();

        //read the rendered view
        filter.Position = 0;
        var reader = new StreamReader(filter, response.ContentEncoding);
        return reader.ReadToEnd();
    }
    finally
    {
        //Clean up.
        if (filter != null)
        {
            filter.Dispose();
        }

        //Now replace the response filter
        response.Filter = oldFilter;
    }
}

It's not perfect. After executing the method you can't perform any redirects anymore because the response has to be flushed and so the headers are already sent. If you find a workaround for this, plese post it here.

Mato
I spotted the same post when I was looking to do the same. As I was trying to return a rendered usercontrol in a Json call, the headers being sent was enough to stop this working for me. Good of you to post this for Adrian though +1
TreeUK
I had the same problem. I solved this by rendering only a partial (to string) instead of rendering a full page. When rendering a partial you don't have to flush the reponse anymore.
Mato