Render a Razor view to string in Asp.net MVC
Today in this article we will see how to render razor view or partial view to string in Asp.net MVC. View or partial view contains generally html tags and razor syntax, if we can convert view into string using C# than we can pass string as a Json Result from controller to view(for Ajax call). Let’s see sample code.
Convert Razor view to string using C#
public static class RazorViewToString
public static string RenderRazorViewToString(this Controller controller, string viewName, object model)
if (controller == null)
throw new ArgumentNullException("controller", "Extension method called on a null controller");
if (controller.ControllerContext == null)
controller.ViewData.Model = model;
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
if (viewResult != null)
using (var sw = new StringWriter())
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
Above class “RazorViewToString” will render MVC’s view or partialview as a string. For that you just need to call “RenderRazorViewToString” method and have to pass arguments as “Controller”, “ViewName” and “model”. Let’s see how to call “RenderRazorViewToString” method from your controller.
Call Render Razor view to string method from you controller
string Enquiry = RazorViewToString.RenderRazorViewToString(this, "~/Views/Home/_TestPartialView.cshtml", Model);
Here “RazorViewToString” class defined as a static so there is no need to create instance of “RazorViewToString” class and can directly call method “RenderRazorViewToString” and have to pass first argument as “this” for controller, second argument as a view or partialview name with it’s full path and last argument as a Model which is strongly typed with your view or partialview. Finally this method will convert view or partial view into string and you can pass converted string as a json from your controller to view or partial view for Ajax call purpose.
What is your opinion ?
Here we have seen example of converting razor view to string in mvc. I hope this piece of code will be very useful to render MVC’s view to string and you will enjoy it. If you have any query and question, you can comment or you can mail me.