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

后端 未结 15 2916
挽巷
挽巷 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 04:56

    This answer is not on my way . This is originally from https://stackoverflow.com/a/2759898/2318354 but here I have show the way to use it with "Static" Keyword to make it common for all Controllers .

    For that you have to make static class in class file . (Suppose your Class File Name is Utils.cs )

    This example is For Razor.

    Utils.cs

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

    Now you can call this class from your controller by adding NameSpace in your Controller File as following way by passing "this" as parameter to Controller.

    string result = RazorViewToString.RenderRazorViewToString(this ,"ViewName", model);
    

    As suggestion given by @Sergey this extension method can also call from cotroller as given below

    string result = this.RenderRazorViewToString("ViewName", model);
    

    I hope this will be useful to you make code clean and neat.

提交回复
热议问题