我可以返回一个包含渲染视图的Json结果吗?
我需要它返回一个提交的表单的新ID以及其HTML和一些其他属性。
另外,当我需要从一个Json对象中的一个动作返回两个(或更多)视图结果时,这也是有帮助的。
谢谢!
解决方法
您还可以将一个PartialViewResult渲染为字符串,然后将此字符串通过JSON传递到您的视图,使用jQuery在您的页面中呈现它。
你可以看到在这篇文章:http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/。
我创建了一个扩展,使其更容易:
public static class MvcHelpers { 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(); } } }
在我的控制器中,我叫它如下:
const string msg = "Item succesfully updated!"; return new JsonResult { Data = new { success = true,message = msg,view = this.RenderPartialView("ProductItemForm",model) },JsonRequestBehavior = JsonRequestBehavior.AllowGet };
其中“this”是控制器的情况下,“ProductItemForm”是我的视图和“模型”是我的productItem对象:)
希望这可以帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。