Mesut
Mesut

Reputation: 1875

How to implement razor.cshtml file within action

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.

Upvotes: 1

Views: 367

Answers (1)

Jan
Jan

Reputation: 16032

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

Upvotes: 1

Related Questions