Sirisha Ancha Team : Web Development Tags : Technology Web Development jQuery MVC

MVC JsonResult: returning view and data at the same time

Sirisha Ancha Team : Web Development Tags : Technology Web Development jQuery MVC

The usual way to return a partial view as a JsonResult to an Ajax call is done as shown below:

Controller:

        public ActionResult AjaxSearch(SearchRequest searchRequest)
        {            
            var model = new SearchModel();            
            .....          
            return PartialView("Search", model);
        }

Script:

           $.ajax({
                url: "Search/AjaxSearch",
                type: 'post',
                datatype: 'application/json',
                data: form.serialize(),
                success: function (data) {
                    $("#showResults").html(data)
                },
                error: function () {
                    alert('Ajax error!');
                }
            });

Here the controller converts the partial view into the corresponding html content while passing it back to the Ajax call. So the data variable returned contains the view and this could be used to populate any element on the view.

If there is a need to pass some more parameters along with the view, you can do the following:

Controller:

        public JsonResult AjaxSearch(SearchRequest searchRequest)
        {            
            var model = new SearchModel();            
            .....
            return Json(new
            {
                view = RenderRazorViewToString(ControllerContext, "SearchResultsList", model)
                , isValid = true
                , itemsCount = model.Items.Count
                ....
            });
        }
        public static string RenderRazorViewToString(ControllerContext controllerContext, string viewName, object model)
        {
            controllerContext.Controller.ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var ViewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
                var ViewContext = new ViewContext(controllerContext, ViewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, sw);
                ViewResult.View.Render(ViewContext, sw);
                ViewResult.ViewEngine.ReleaseView(controllerContext, ViewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }

Script:

           $.ajax({
                url: "Search/AjaxSearch",
                type: 'post',
                datatype: 'application/json',
                data: form.serialize(),
                success: function (data) {
                    if (data.IsValid && data.itemsCount == 0) {
                        ...
                    }
                    else {                       
                        $("#showResults").html(data);
                    }
                },
                error: function () {
                    alert('Ajax error!');
                }
            });

This feature could be extended to return multiple views with multiple parameters.