ASP.NET MVC - 将Json结果与ViewResult结合使用

ela*_*ado 30 asp.net-mvc json partial-views

我可以返回包含渲染视图的Json结果吗?

我需要它来返回提交表单的新ID以及HTML和其他一些属性.

当我需要从Json对象中的一个动作返回两个(或更多)视图结果时,这也很有用.

谢谢!

Die*_*ano 41

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.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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
           };
Run Code Online (Sandbox Code Playgroud)

Where "this" is the controller in the case, "ProductItemForm" is my view and "model" is my productItem object :)

Hope this helps ;)