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

后端 未结 15 3009
挽巷
挽巷 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条回答
  •  我寻月下人不归
    2020-11-21 05:17

    This works for me:

    public virtual string RenderView(ViewContext viewContext)
    {
        var response = viewContext.HttpContext.Response;
        response.Flush();
        var oldFilter = response.Filter;
        Stream filter = null;
        try
        {
            filter = new MemoryStream();
            response.Filter = filter;
            viewContext.View.Render(viewContext, viewContext.HttpContext.Response.Output);
            response.Flush();
            filter.Position = 0;
            var reader = new StreamReader(filter, response.ContentEncoding);
            return reader.ReadToEnd();
        }
        finally
        {
            if (filter != null)
            {
                filter.Dispose();
            }
            response.Filter = oldFilter;
        }
    }
    

提交回复
热议问题