0

I would like to have my Razor View return a string of the html it renders, so that the controller would return the rendered html string from the View and not just the view. There is no native method I can find in ASP.NET MVC to do this. Are there any workarounds for this?

By way of illustrative example :

 public ActionResult Index()
        {
            return View().ToString; //View has no ToString() method but this is what I am trying to do
        }

1 Answer 1

3

You can use Html.Partial to return an MvcHtmlString of the view.

You can find the Partial method in System.Web.Mvc.Html.PartialExtensions.

There's more information here about this method: http://msdn.microsoft.com/en-us/library/ee402898.aspx

I personally use this for my RenderPartials (plural) extension method:

   public static void RenderPartials<T>(this HtmlHelper helper, 
            string partialViewName, IEnumerable<T> models, string htmlFormat)
        {
            if (models == null)
                return;

            foreach (var view in models.Select(model => 
                  helper.Partial(partialViewName,model, helper.ViewData)))
            {
                helper.ViewContext.HttpContext.Response
                  .Output.Write(htmlFormat, view);
            }
        }

Update

To render your view to a string in your controller you can do something like this (although it seems like a bit of a hack):

var htmlHelper = new HtmlHelper(new ViewContext(), new ViewPage());
var viewString = htmlHelper.Partial("PartialViewName");

The reason I say it's a bit of a hack is because HtmlHelper is designed to be used in your views and not in your controllers or models. That being said, if it works and there isn't an alternative to stringify a parsed view it might be of use to you.

Given the amendment to your question you'd be looking for something like this:

public string Index()
{
    var htmlHelper = new HtmlHelper(new ViewContext(), new ViewPage());
    return htmlHelper.Partial("PartialViewName");
}

If the above code doesn't create the htmlHelper correctly you can create it like this instead:

TextWriter writer = new StringWriter();
var htmlHelper = new HtmlHelper(new ViewContext(ControllerContext, 
                new RazorView(ControllerContext, "","",true,null), 
                new ViewDataDictionary(), 
                new TempDataDictionary(), writer), new ViewPage());
1
  • Would you mind showing how I could use this within a Controller to simply output the html string generated by the View (I amended my question).
    – Judo
    Commented Apr 12, 2012 at 10:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.