我在MVC 4中进行实验,如果可以将字符串转换为视图并从Controller返回,我正在游荡。从字符串创建一个视图
例如,我有一个方法,将查看内容读入字符串。我想在渲染它之前处理该字符串。所以我想让Controller将修改过的字符串输出为View。
这甚至可能吗?
只是为了说明一下,这将发生在剃刀做出任何更改之后。我确实有一个方法可以将最终的View视为一个字符串。
编辑
我有以下方法:
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();
}
}
返回最终渲染视图(什么是真正要在浏览器中显示)为一个字符串。
我需要做相反的事情。有一个字符串,输出一个View。
所以,如果我有以下cshtml
:
<!doctype html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
Hello World
</body>
</html>
上述函数将返回喜欢的字符串:
"<!doctype html><head><title>MyActualTitle</title></head><body>Hello World</body></html>"
现在我想的是利用这个字符串,操纵它和渲染。例如,我想更改Hello World
。我知道我可以用Razor
这样做,我只是在流浪,如果我可以用另一种方法做到这一点。
不明确。您希望控制器处理_after_剃刀?什么样的字符串,什么样的视图? –
我真的是把视图变成一个字符串,我想以另一种方式做。 –
所以,你想渲染一个视图到一个字符串..修改该字符串..然后渲染新的字符串作为视图? –