I'm wondering how can I render a partial view to be used in a JsonResult in my controller?
我想知道如何在控制器的JsonResult中呈现要使用的部分视图?
return Json(new
{
Html = this.RenderPartialView("_EditMovie", updatedMovie),
Message = message
}, JsonRequestBehavior.AllowGet);
}
}
1 个解决方案
#1
3
RenderPartialView
is a custom extension method which renders a view as a string
.
RenderPartialView是一种自定义扩展方法,它将视图呈现为字符串。
It wasn't mentioned in the article (what you have referred originally) but you find it in the sample code attached to the article. It can be found under the \Helpers\Reders.cs
文章中没有提到它(您最初提到的内容),但是您可以在文章附带的示例代码中找到它。它可以在“帮助”\ reders.c中找到。
Here is code of the method in question:
下面是这个方法的代码:
public static string RenderPartialView(this Controller controller,
string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData
.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines
.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext,
viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
#1
3
RenderPartialView
is a custom extension method which renders a view as a string
.
RenderPartialView是一种自定义扩展方法,它将视图呈现为字符串。
It wasn't mentioned in the article (what you have referred originally) but you find it in the sample code attached to the article. It can be found under the \Helpers\Reders.cs
文章中没有提到它(您最初提到的内容),但是您可以在文章附带的示例代码中找到它。它可以在“帮助”\ reders.c中找到。
Here is code of the method in question:
下面是这个方法的代码:
public static string RenderPartialView(this Controller controller,
string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData
.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines
.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext,
viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}