1 回答
TA贡献1796条经验 获得超4个赞
使用此方法将视图呈现为字符串:
public static string RenderViewToString(ControllerContext context, string viewPath, object viewModel = null, bool partial = false)
{
// get the ViewEngine for this view
ViewEngineResult viewEngineResult = null;
if (partial)
viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
else
viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
if (viewEngineResult == null)
throw new FileNotFoundException("View cannot be found.");
// get the view and attach the model to view data
var view = viewEngineResult.View;
context.Controller.ViewData.Model = viewModel;
string result = null;
using (var sw = new StringWriter())
{
var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
view.Render(ctx, sw);
result = sw.ToString();
}
return result;
}
如果您致电:
@foreach (var item in Model.SomeIEnumerableModel)
{
@Html.Partial("~/Views/SomePath/SomeViewTwo.cshtml", item);
}
在“父局部视图”中。
可以使用这个在控制器中调用它(假设您从 ajax 请求返回 json,并且该RenderViewToString方法位于调用控制器中):
public ActionResult TestViewToString()
{
var viewModel = new TestViewModel();
// Populate ViewModel here ...
string data = RenderViewToString(ControllerContext, "~/Views/SomePath/SomeViewOne.cshtml", viewModel, true);
return Json(data, JsonRequestBehavior.AllowGet);
}
- 1 回答
- 0 关注
- 174 浏览
添加回答
举报