ASP.NET MVC - 结合JSON结果用的ViewResult [英] ASP.NET MVC - Combine Json result with ViewResult
问题描述
我可以返回也包含了渲染视图一个JSON结果?
Can I return a Json result that contains also a rendered view?
我需要它与它的HTML和其他一些属性一起返回提交表单的新ID。
I need it to return the new ID of a submitted form along with its HTML and some other properties.
也是可以帮助时,我需要返回一个JSON对象中从一个操作两个(或更多)查看结果。
Also that can be helpful when I need to return two (or more) view results from one action inside a Json object.
谢谢!
推荐答案
您也可以呈现PartialViewResult为一个字符串,然后通过JSON传递这个字符串你的看法,使用jQuery在你的页面渲染它。
You can also render a PartialViewResult to a string, and then pass this string via JSON to your view, rendering it in your page using jQuery.
您可以看到,在这个帖子:<一href=\"http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/\">http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/.
You can see that in this post: http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/.
我创建了一个扩展,使其更容易:
I've created an extension to make it easier:
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();
}
}
}
在我的控制器我叫它如下:
In my controller I call it as follows:
const string msg = "Item succesfully updated!";
return new JsonResult
{
Data = new
{
success = true,
message = msg,
view = this.RenderPartialView("ProductItemForm", model)
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
在哪里这的情况下,控制器,ProductItemForm是我的看法和模式是我productItem对象:)
Where "this" is the controller in the case, "ProductItemForm" is my view and "model" is my productItem object :)
希望这有助于;)
这篇关于ASP.NET MVC - 结合JSON结果用的ViewResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!