如何在action中实现razor.cshtml文件

时间:2012-11-21 14:17:08

标签: asp.net asp.net-mvc razor asp.net-mvc-4

我想在action中实现view.cshtml文件,然后将其结果作为字符串获取,但不从action方法返回为ActionResult。
用代码解释,而不是:

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

必须如此:

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

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

我使用类似的东西将我的应用程序内的视图呈现为字符串:

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