I am experimenting in MVC 4, and i was wandering if it is possible to turn a string into a View and return this from the Controller.
For instance, i have a method that reads the View contents into a string. I would like to process that string before rendering it. So i would like the Controller to output the modified string as a View.
Is this even possible?
Just to make a note, this will happen after Razor has made any changes. I do have a method that gets the final View into a string.
Edit
I have the following method:
public static string RenderViewToString(this Controller controller, string viewName, object model)
{
controller.ViewData.Model = model;
try
{
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, null);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
return sw.ToString();
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
which returns the finally rendered View (what is actually going to be displayed in the browser) into a string.
I need to do the opposite. Having a string, output a View.
So if i have the following cshtml
:
<!doctype html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
Hello World
</body>
</html>
The above function will return a string like:
"<!doctype html><head><title>MyActualTitle</title></head><body>Hello World</body></html>"
Now what i want is take this string, manipulate it and render it. For instance i want to change the Hello World
. I know i can do this with Razor
, i was just wandering if i can do this with another method.
My HTML
");` – James Oct 07 '13 at 10:16