简体   繁体   中英

asp.net mvc, returning multiple views as JSON

Is it possible to return 2 separate views to an ajax call in Asp.net?

for example, if foo1 and foo2 are 2 ActionResult methods each returning a view?

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?

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.

For this you need to do following things:

1.You need some method in which you can pass your viewname along with object model. 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:

 [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.

Hope this is what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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