I need to generate html (for the body of an email message) specific to a Customer
object
I thought of making a View
that gets a Customer
object and renders the appropriate text.
Is there a way to call a view and get the rendered output without associating it to a controller action?
Ideally in pseydocode I would do something like this
customer = new Customer();
view = new GetCustomerEmailBodyView(customer);
string htmlBody = view.SomeFunctionToRenderViewAndGetOutput()
I have found a solution to get the HTML of a view here that has an action returning a StringResult (inherits from ViewResult) instead of ActionResult which exposes an Html
property.
However I still have to make a custom action to call it, and I don't like the fact that it depends on the ControllerContext making it hard to test it.
Is what I am requesting against the MVC principals? How should my code be structured for this scenario?
Original code from here
Are you saying that you want some program to be able to leverage a View without being in a controller context at all, or are you saying that you want to be able to render a view into a string from within a controller, without calling some other controller?
For the former, I can't be of much assistance, but for the latter, we have this method in the base controller type that we inherit with all our other controllers:
Usage:
We actually use this in an event-based AJAX model, where most of our actions actually just return an AJAX-encoded list of client-side events, and some of those client-side events may be to update a particular DOM element with the string produces by rendering this partial view.