We are currently trying to create an action that returns a JsonResult and at certain times that action should also return some HTML inside it along with the other data. Is it possible to generate the HTML from another action that returns a PartialViewResult?
Asked
Active
Viewed 228 times
0
-
2possible duplicate of [Render a view as a string](http://stackoverflow.com/questions/483091/render-a-view-as-a-string) – ramiramilu Jul 01 '15 at 12:19
-
not really a duplicate as that question is view specific. this is about rendering the result of an action – harryovers Jul 01 '15 at 13:16
1 Answers
0
I think this is what you want to achieve.
Generate HTML from another action sounds strange.
You may get the same model from your repository and then render the same PartialView. You will need a method like the following.
// in a RenderingHelper class
public static string RenderViewToString(ControllerContext context, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = context.RouteData.GetRequiredString("action");
ViewDataDictionary viewData = new ViewDataDictionary(model);
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
ViewContext viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
And then you will render the partial view accordingly:
string renderedHtml = RenderingHelper.RenderViewToString(this.ControllerContext, "~/Views/MyController/MyPartial", viewModel);
Where viewModel
is the model used by "other action" too and "~/Views/MyController/MyPartial"
is the partial view used by "other action" too.

Razvan Dumitru
- 11,815
- 5
- 34
- 54