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?

有帮助吗?

解决方案

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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top