0

Is there any way to return the View("controller", model) with JSON result? I've done like this(see code below) but it returns me an error.

    if (thereserror == true)
    {
        return Json(new
        {
            view = RenderRazorViewToString(ControllerContext, "Index", model),
            isValid = false,
            description = "Error!",
            JsonRequestBehavior.AllowGet
        });
    }
    else
    {
        return Json(new
        {
            view = RenderRazorViewToString(ControllerContext, "Index", model),
            isValid = true,
            description = "Hey!",
            JsonRequestBehavior.AllowGet
        });
    }

    private 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();
        }
    }

For my AJAX I'm doing like this:

 $.ajax({
        type: "GET",
        url: "/serviceentry/getservice",
        data: ({ "SONumber": soNumber }),
        success: function (data) {
            if (data.isValid) {
                //I don't know what to put here
            };
        },
        error: function () {
            alert('error');
        }
    });

I saw something like this but I don't know what to do: MVC Return Partial View as JSON

Heimi
  • 126
  • 1
  • 12
Zach
  • 317
  • 1
  • 3
  • 16
  • You just need to redirect to specific view after you get data from ajax is this you want ? – Saineshwar Bageri - MVP Nov 30 '17 at 06:44
  • 1
    What are you wanting to do with the partial view? To include it in the DOM you might do say `$(someElement).html(data.view);` –  Nov 30 '17 at 06:49
  • And what error are you getting? –  Nov 30 '17 at 06:51
  • Note you have the `JsonRequestBehavior.AllowGet` in the wrong place - its `return Json(new { view = ..., description = "Hey!" }, JsonRequestBehavior.AllowGet);` –  Nov 30 '17 at 06:52
  • @StephenMuecke, thanks for correcting me. Actually that's one of my error. Allow Get using JsonRequestBehavior. But my concern is that, in my controller I can retrieved data from my dataset and put it in my **Model**. I want it to return just like this behavior **return View("Index", model)** – Zach Nov 30 '17 at 07:00
  • So what problem are you having? And you still have not stated what your want to do with the partial view you returned –  Nov 30 '17 at 07:02
  • @StephenMuecke I just want to return View and data (json result) at the same time. Just like this one [link](https://www.wiliam.com.au/wiliam-blog/mvc-jsonresult-returning-view-and-data-at-the-same-time) – Zach Nov 30 '17 at 07:08
  • I know. But what is your problem! –  Nov 30 '17 at 07:09
  • @StephenMuecke. I change the **if** logic. I think I got it now. I just want to return JSON result with "error" description. What I did was. `if (!isError) { return View("Index", model); } else { return Json(new { view = RenderRazorViewToString(ControllerContext, "Index", model), isValid = false, description = errResult }, JsonRequestBehavior.AllowGet); }` – Zach Nov 30 '17 at 07:24

1 Answers1

1

JSON you are returning contains 4 properties, the way you are accessing isValid, similarly access the View.

$.ajax({
        type: "GET",
        url: "/serviceentry/getservice",
        data: ({ "SONumber": soNumber }),
        success: function (data) {
            if (data.isValid) {
                //Element- Where you want to show the partialView
                $(Element).html(data.view)
            };
        },
        error: function () {
            alert('error');
        }
    });

PS: Also Pointing the wrong placement of JSONRequestBehavior.

if (thereserror == true)
    {
        return Json(new
        {
            view = RenderRazorViewToString(ControllerContext, "Index", model),
            isValid = false,
            description = "Error!"
        },JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(new
        {
            view = RenderRazorViewToString(ControllerContext, "Index", model),
            isValid = true,
            description = "Hey!"
        },JsonRequestBehavior.AllowGet);
    }

    private 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();
        }
    }
Kumar_Vikas
  • 837
  • 7
  • 16
  • Is it possible to return the whole page with model value not just the element? – Zach Nov 30 '17 at 07:36
  • Since you are using AJAX here, its better that you return JSON data. You just have toinclude html(view) as one of the property in your json data. – Kumar_Vikas Nov 30 '17 at 08:57
  • @Zach Yes, It's possible. You can return your html with model. Create a partial view and return the partial view with model instead of json result. – Jibin Balachandran Nov 30 '17 at 10:29
  • @JibinBalachandran OP needs other properties like `isValid` , `description`(used in ajax success part). So returning just the html wont serve his cause. – Kumar_Vikas Nov 30 '17 at 13:43