简体   繁体   English

asp.net mvc,以JSON返回多个视图

[英]asp.net mvc, returning multiple views as JSON

Is it possible to return 2 separate views to an ajax call in Asp.net? 是否可以在Asp.net中将2个单独的视图返回给ajax调用?

for example, if foo1 and foo2 are 2 ActionResult methods each returning a view? 例如,如果foo1和foo2是2个分别返回视图的ActionResult方法?

return Json(new { a = foo1(), b = foo2() });

currently attempting this, the end result is that javascript gets it back as a class object rather then the actual view, anybody know how to get the resulting rendered html instead? 当前正在尝试此操作,最终结果是javascript将其作为类对象而不是实际视图重新获得,有人知道如何获取最终呈现的html吗?

EDIT: I guess what I'm actually going for, is there a way for me to return the rendered view in string format? 编辑:我猜我实际上要做什么,有没有办法让我以字符串格式返回渲染视图?

Yes their is a way of returning view in string format. 是的,它们是一种以string格式返回视图的方法。

For this you need to do following things: 为此,您需要执行以下操作:

1.You need some method in which you can pass your viewname along with object model. 1.您需要一些方法,您可以在其中传递您的视图名称和对象模型。 For this please refer below code and add to your helper class. 为此,请参考下面的代码并添加到您的帮助器类中。

 public static class RenderViewLib
        {
            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();
                }
            }
        }

The above code will return your view in string format. 上面的代码将以字符串格式返回您的视图。

2.Now call above method from your json call like this: 2.现在从您的json调用中调用上述方法,如下所示:

 [HttpPost]
    public JsonResult GetData()
    {
        Mymodel model = new Mymodel();
        JsonResult jr = null;

        jr = Json(new
        {
            ViewHtml = this.RenderPartialView("_ViewName", model),
            ViewHtml2 = this.RenderPartialView("_ViewName2", model),
            IsSuccess = true
        }, JsonRequestBehavior.AllowGet);

        return jr;
    }

and you will get your view as string format from your json call. 并且您将从json调用中以string格式获取视图。

Hope this is what you are looking for. 希望这是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM