1

I've searched for hours and I just do not have an idea of how to solve this.

I have a Winkelwagen Controller:

    [ChildActionOnly]
    public ActionResult WinkelwagenPartial()
    {
        // Get the content of the cart
        OrderregelLijst winkelwagenInhoud = new OrderregelLijst
        {
            Orderregels = (List<Orderregel>)Session["winkelwagen"]
        };

        return PartialView(winkelwagenInhoud);
    }

I load the Partial View in my main layout like this:

                <div id="winkelwagenContainer">
                @{
                    Html.RenderAction("WinkelwagenPartial", "Winkelwagen");
                }
                </div>

This all works fine, the problem now is: How do I refresh my partial view after the content of the shopping cart changes?

I've written the following in jQuery:

        $.ajax({
            url: '/WinkelWagen/WinkelwagenPartial',
            success: function (data) {
                alert(data);
            }
        });

When I add something to the cart or delete something from it, I want the partial view to update. I get the following error though:

The action 'WinkelwagenPartial' is accessible only by a child request.

Which I can understand, since partial views can't be located directly. My question now is though, how can I possibly refresh my partial view?

user1796440
  • 366
  • 3
  • 11

2 Answers2

0

You need to create a different Layout which will only load the contents of the partial, then call load the Partial via AJAX using that Layout.

Joshua
  • 3,615
  • 1
  • 26
  • 32
0

In your ajax call, you could call a JsonAction method in the controller that in turn renders the partial view to a string.

    public JsonResult GetWinkleWagonPartial() {
        return Json(RenderPartialViewToString("WinkelwagenPartial", null), JsonRequestBehavior.AllowGet);
    }

    private string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
Michael Finger
  • 1,110
  • 9
  • 9