Generate HTML string for a MVC View

Sometimes you don’t want to render the view on the standard output stream but you need it to return the output HTML of a view for a JSON call. So, instead of adding the ActionResult of that view to the JSON property, we can force the view to return the output as a string and pass that string as one of the JSON property.
Following Code sample can be used to retrieve the HTML string of a given view and pass the model data to it. The controller context is a required parameter and it can easily be retrieved by the controller.ControllerContext property of the caller.

/// <summary>
/// Generates the HTML string represenation, of a target view.
/// </summary>
/// <param name="c">Controller context is required.</param>
/// <param name="viewName">Target view name.</param>
/// <param name="data">Data object for the view.</param>
/// <returns>HTML string output of the actual view.</returns>
protected string ConvertViewToHtmlString( ControllerContext c, string viewName, object data )
    if ( data != null )
        //set view data notifications
        ViewData.Model = data;

        StringWriter output = new StringWriter();
        //find the view to general html string
        ViewEngineResult result = ViewEngines.Engines.FindView( c, viewName, "" );
        ViewContext viewContext = new ViewContext( c, result.View, ViewData, TempData, output );

            //render the view to stringWriter, rather than on Response stream
            result.View.Render( viewContext, output );
            //release the view so that it can be used by other controllers
            result.ViewEngine.ReleaseView( c, result.View );

        //html string for the view
        return output.ToString();
        return "";

Tags: ,

About prres

I have been working with Microsoft Tools and Technologies for 9 years. Most of my work include architecting and developing with C#, ASP.Net, Silverlight and SQL Server.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: