Data Haunting

Easy Solutions Destination


Render a Razor view to string in MVC

Today in this article we will see how to render razor view or partial view to string in 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#

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

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.

Leave a Reply