1

I'd like to implement view.cshtml file within action and then get its result as string, but not returning as ActionResult from action method.
To explain with code, instead of:

public ActionResult Tesst()
        {
            // return ViewResult
            return View();
        }

İt must be so:

public string Test()
        {
            string viewResult = string.Empty;
            // implement "test.cshtml" and get its result as string
            // assign result to viewResult variable
            return viewResult;
        }

Any helps would be appreciated.

Mesut
  • 1,845
  • 4
  • 24
  • 32

1 Answers1

1

I use something like this to render a view inside my app to a string:

public static string RenderViewToString(System.Web.Mvc.Controller controller,
                                  string viewName, string layout, object model)
{
    controller.ViewData.Model = model;
    using (StringWriter sw = new StringWriter())
    {
        ViewEngineResult viewResult =
                   ViewEngines.Engines.FindView(
                           controller.ControllerContext, viewName, layout);
        ViewContext viewContext = new ViewContext(
                   controller.ControllerContext, 
                   viewResult.View, controller.ViewData, 
                   controller.TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}
Jan
  • 15,802
  • 5
  • 35
  • 59