I need to use the html generated by a razor template in one of my controllers, an abstract one actually to handle ajax lists. That way I can have a generic ajax list implementation which will work for any type of model, and provide the standard operations like add/edit/delete ...
Since I'd like to generate the list elements on the server, I thought I could make razor templates for each element, and then return the generated html (for a new element, or for editing an element) in a JSON object like this:
- a flag to tell if the operation was successful
- an error field to describe the error (if there was one)
- the generated html
At first I thought about instantiating an HtmlHelper
(as explained here: HtmlHelper in controller) and using the EditorFor
method, but I'm wondering if this a good way to achieve this, since creating an instance of HtmlHelper
seems to be quite a time consuming operation.
Is there a simple way to execute the right razor template and get the html in a string?
Also is there a better way to implement such a generic behavior?
I created a method that does the trick. My reason for creating the method was the same as yours; I wanted to return a
JsonResult
that contained not only the markup but some other data as well.I placed this method in my base controller so all my controllers have access to it.