Does anybody know how to get the generated html of a view inside an action?
Is it something like this:
public ActionResult Do()
{
var html = RenderView("hello", model);
...
}
Does anybody know how to get the generated html of a view inside an action?
Is it something like this:
public ActionResult Do()
{
var html = RenderView("hello", model);
...
}
I use a static method in a class I called
Utilities.Common
I pass views back to the client as properties of JSON objects constantly so I had a need to render them to a string. Here ya go:This will work for full views as well as partial views, just change
ViewEngines.Engines.FindPartialView
toViewEngines.Engines.FindView
.The accepted answer by @Chev above is good, but I wanted to render the result of a specific action, not just a particular view.
Also, I needed to be able to pass parameters to that action rather than rely on injecting a model.
So I came up with my own method, that I put in the base class of my controllers (making it available to them all):
Suppose I have an action called
Foo
that takes a model object and some other parameters, which together influence what view will be used:Now, if I want to get the result of calling action
Foo
, I can simply get theViewResult
by invoking theFoo
method, and then callRenderViewResultAsString
to get the HTML text: