Wednesday, April 19, 2023

How to render a Razor view to string in ASP.net MVC

 Sometimes we need to get the Razor view to a string, in order to use it for various purposes. I had a requirement where I needed to generate a PDF file from the Razor view.

I used below method to convert the Razor view to a string and used this string to generate a PDF file.

Below is the detailed explanation of that:

Steps:

1. Get the viewResult using the view name.

2. Get the viewContext using the view.

3. Render the data to the StringWriter class object using the viewResult and viewContext.

4. Finally release the view and get the string from StringWriter class object.

public string RenderRazorViewToString(this Controller controllerName, string viewName, object model)

        {

            controller.ViewData.Model = model;

            //used a StringWriter to get the Razor contents into it.

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

            }

        }


This worked like a charm for me. Now you can use this return string for your custom needs.

Hope this helps somebody out there.