Render Action to String

房东的猫 提交于 2019-12-13 12:33:12

问题


I have an action that return a partialview and I want to render the action result to string, I tried lot of examples show on others threads about this subject, but all have the same behavior, executes de View but not the action, is this possible?

Example: 1) Action - Partial View to render to string

    public PartialViewResult Email(string Subject, string Body)
    {
        ViewBag.Subject = Subject;
        ViewBag.Body = Body;

        ViewBag.ExtraData = Session["ExtraData"];

        return PartialView();
    }

2) Partial View

@{
    Layout = null;
    string Subject = (string)@ViewBag.Subject
    string Body = (string)@ViewBag.Body
}
<html>
<head>
    <title>@Subject</title>
</head>
<body style="margin:0px">
       @Body
</body>

3) Controller class obtaining string action result

var emailHTML = RenderViewToString(ControllerContext, "Email", new string[] { subject, msg });

4) Helper method from stackoverflow thread

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

If I debug the code, it goes directly to the View with no ViewBag data, and doesn't execute the Email Action method.

Any idea?


回答1:


That helper is useful for rendering a view directly, but not an action. That is, is doesn't even call that action that you want it to call. Instead, that code just finds a view and renders it directly to a writer with the supplied model.

What we want to do is actually call the Email() PartialViewResult and render that.

Observe:

using (var sw = new StringWriter())
{
  PartialViewResult result = Email("Subject", "Body");

  result.View = ViewEngines.Engines.FindPartialView(ControllerContext, "Email").View;

  ViewContext vc = new ViewContext(ControllerContext, result.View, result.ViewData, result.TempData, sw);

  result.View.Render(vc, sw);

  var html = sw.GetStringBuilder().ToString();
}


来源:https://stackoverflow.com/questions/22774856/render-action-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!