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());