gpt4 book ai didi

.net - 如何在 Controller 中为 Json 呈现部分 View

转载 作者:行者123 更新时间:2023-12-04 05:35:48 27 4
gpt4 key购买 nike

如何呈现要在 Controller 的 JsonResult 中使用的局部 View ?

return Json(new
{
Html = this.RenderPartialView("_EditMovie", updatedMovie),
Message = message
}, JsonRequestBehavior.AllowGet);

最佳答案

RenderPartialView是一种自定义扩展方法,它将 View 呈现为 string .

没有提到 in the article (您最初提到的内容)但您可以在文章所附的示例代码中找到它。
它可以在\Helpers\Reders.cs 下找到

这是有问题的方法的代码:

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();
}
}

关于.net - 如何在 Controller 中为 Json 呈现部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955015/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com