How to render an ASP.NET MVC view as a string?

后端 未结 15 2928
挽巷
挽巷 2020-11-21 04:40

I want to output two different views (one as a string that will be sent as an email), and the other the page displayed to a user.

Is this possible in ASP.NET MVC bet

15条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 05:10

    Here's what I came up with, and it's working for me. I added the following method(s) to my controller base class. (You can always make these static methods somewhere else that accept a controller as a parameter I suppose)

    MVC2 .ascx style

    protected string RenderViewToString(string viewPath, T model) {
      ViewData.Model = model;
      using (var writer = new StringWriter()) {
        var view = new WebFormView(ControllerContext, viewPath);
        var vdd = new ViewDataDictionary(model);
        var viewCxt = new ViewContext(ControllerContext, view, vdd,
                                    new TempDataDictionary(), writer);
        viewCxt.View.Render(viewCxt, writer);
        return writer.ToString();
      }
    }
    

    Razor .cshtml style

    public string RenderRazorViewToString(string viewName, object model)
    {
      ViewData.Model = model;
      using (var sw = new StringWriter())
      {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                 viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                     ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
      }
    }
    

    Edit: added Razor code.

提交回复
热议问题