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
}
You can use
Html.Partialto return anMvcHtmlStringof the view.You can find the
Partialmethod inSystem.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:
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):
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:
If the above code doesn’t create the htmlHelper correctly you can create it like this instead: