So this might sound a bit odd, but essentially I'm trying to render a view ahead of time in a controller so I can pass it to a property in a model. (This is so I can later pass the view's rendered HTML to a service call, so I have a reason.) I have code that almost accomplishes this (adapted from this answer), with the bad side effect of returning a view that's been rendered twice:
public ActionResult Action(object paramater)
{
var model = new MyModel(parameter);
ViewResult view = View("~/... path to view .../View.cshtml", model);
string data;
using (var sw = new StringWriter())
{
view.ExecuteResult(ControllerContext);
var viewContext = new ViewContext(ControllerContext, view.View, ViewData, TempData, sw);
view.View.Render(viewContext, sw);
data = sw.ToString();
}
model.ViewRender = data;
return view;
}
This successfully puts a copy of the view's HTML in the model, but the view itself is rendered twice (so it seems), so I get a webpage back that is two copies of the same thing, one on top of the other.
I've tried a couple different ways of returning the view without this side effect—making a new one entirely with return View(model)
, going into another method—nothing has worked so far.