ricky89
ricky89

Reputation: 1396

Call Controller Action using Jquery

I am trying to reload a particular 'div' () when the user adds a item to a shopping cart. I have some Jquery which I want to run on the click event. It needs to call a post action (which is working) and then reload everything within a "reload" div (only a render action).

This reload piece seems to work also, but doesn't just reload the div, but also a portion of the current page. Given this it must be the jquery which is incorrect. Any help with what I have done wrong would be appreciated.

I will try and include only the necessary pieces of code below:

Load the partial view in the layout view:

<div id="reload">
    @{Html.RenderAction("_PartialView","Controller");}
</div>

Link user clicks on. Click event listened for by Jquery:

<p class="button">
    <a href="#" class="AddToCart" data-id="@item.ItemId"> Add To Basket</a>  
</p>

Action called by the Jquery on click event:

[ChildActionOnly]
        public ActionResult _CartSummary()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);

            ViewData["CartCount"] = cart.GetCount();

            return PartialView("_CartSummary.cshtml");
        }

JQuery called on click event:

    $(function () {
    $(".AddToCart").click(function () {
        var addToCart = $(this).attr("data-id");
        if (addToCart != '') {
            $.post("/ShoppingCart/AddToCart", { "id": addToCart }).success(function() {
                $("#cartSummary").fadeOut();
                $("#cartSummary").fadeIn().load('@Url.Action("_CartSummary","ShoppingCart")');
            });
            return false;
        };
    });
});

when calling the JQuery above, the url that is returned by $("#cartSummary").fadeIn().load('@Url.Action("_CartSummary","ShoppingCart")') is localhost/Store/@Url.Action(%22_CartSummary%22,%22ShoppingCart%22. As expected this url is not found. The correct url would be localhost/ShoppingCart/_CartSummary. Seems that @Url.Action is not being processed and just passed in as the name of the Action.

Upvotes: 0

Views: 1843

Answers (3)

ricky89
ricky89

Reputation: 1396

So a while of playing around with this problem and using the answers supplied as a basis, I have a working solution I am happy with. It's most definitely not the cleanest way to do this I'm sure; but results are what I wanted. Hopefully this may help someone in the furture.

Jquery in the view:

<script>
$(function () {
    //On click of .AddToCart
    $(".AddToCart").click(function () {
        // Get the id from the link
        var addToCart = $(this).attr("data-id");
        if (addToCart != '') {
            $.post("/ShoppingCart/AddToCart", { "id": addToCart }).success(function (data) {
                $('#cart-status').fadeIn().html('Cart  ' + '<span class="badge">' + data.CartCount + '</span>');
            });
            return false;
        };
    });
});
</script>

Code in the partial View

<ul class="nav navbar-nav" style="margin-top:-15px;">
    <li><a href="/ShoppingCart?Length=12" id="cart-status">Cart  <span class="badge">@ViewData["CartCount"]</span></a></li>
</ul>

and finally the controller:

public ActionResult AddToCart(int id)
        {
            //Code...

            var results = new ViewModel
                {
                    Message = Server.HtmlEncode(addedItemName) +
                        " has been Added to your shopping cart.",
                    CartCount = cart.GetCount(),
                };
            return Json(results);
        }

Upvotes: 0

beautifulcoder
beautifulcoder

Reputation: 11330

When you load, it needs to point to a partial. Like

$("#cartSummary").fadeIn().load('@Url.Action("_PartialView", "Controller")');

Finally, when you send a $.post(), remember that it is asynchronous. A better approach might be:

$.post("/ShoppingCart/AddToCart", { "id": addToCart }).success(function () {
    $("#cartSummary").fadeIn().load('@Url.Action("_PartialView", "Controller"'));
});

If your jQuery is in a separate file as it should be, do this in *.cshtml.

<div id="cartSummary" data-url="@Url.Action("_PartialView", "Controller")"></div>

And in jQuery:

$("#cartSummary").fadeIn().load($("#cartSummary").data("url"));

The basic technique is to treat HTML as a repository. This is where we store all our dynamic information coming from the server.

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

$(document).ready(function () {
    $(".AddToCart").click(function () {
        var addToCart = $(this).attr("data-id");
        if (addToCart != '') 
        {
            $.post("/ShoppingCart/AddToCart", { "id": addToCart },function(data){
                 $("#cartSummary").html(data);
                 $("#cartSummary").fadeOut();
                 return false;
            }); 

        }
    });
});

Upvotes: 0

Related Questions