0

Question Background:

I am trying to pass two parameters (product name and price) from a View to an 'AddToCart' method on my MVC Controller. I'm doing this by passing the parameters to a JQuery Ajax function.

Issue:

Currently when clicking the 'Add To Cart' button 'link' the script is not being triggered. There is no error but the process is not taking place.

Here is the code:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

//View:
<h3 class="panel-title boldFeatures" id="name">@((ViewBag.data as List<LoginTest.Models.HomePageItem>).First().ProductName)</h3>

<p id="price">@((ViewBag.data as List<LoginTest.Models.HomePageItem>).First().productPrice)</p>

<a class="btn btn-primary btn-block" id="addToCart">Test</a>



//Script:
<script>
    $("#addToCart").on('click',function (e) {
        e.preventDefault();
        $.ajax({
            url: '/HomePage/AddToCart',
            data: { name: $('#name').text(), qty: $('#price').text() },
        });

    });
</script>



//Method on controller:
 public void AddToCart(string name, string qty)
    {
       //Logic for adding to the cart.
    }
tereško
  • 58,060
  • 25
  • 98
  • 150
user1352057
  • 3,162
  • 9
  • 51
  • 117

2 Answers2

0

Removed the trailing comma after data object. Also added POST method to your ajax call.

   <a href="#" class="btn btn-primary btn-block" id="addToCart">Test</a>



    //Script:
    <script>
        $("#addToCart").on('click',function (e) {
            e.preventDefault();
            $.ajax({
                url: '/HomePage/AddToCart',
                type: 'POST',
                data: { name: $('#name').text(), qty: $('#price').text() }
            });

        });
    </script>
Christopher Marshall
  • 10,678
  • 10
  • 55
  • 94
0
...
<a class="btn btn-primary btn-block" id="addToCart" href="javascript:void(0);">Test</a>

...
$("#addToCart").click(function(e){
  $.ajax({
    url: '/HomePage/AddToCart',
    data: { name: $('#name').text(), qty: $('#price').text() } // ,
});

...
Tracker1
  • 19,103
  • 12
  • 80
  • 106
  • They already have a preventDefault on the click event. That's just muddying up the markup. – Christopher Marshall Nov 25 '14 at 22:12
  • The markup change explicitly indicates that it should never function client-side... If there's an error in the bind method, or something above the bind method, then the preventDefault will fail. – Tracker1 Nov 25 '14 at 22:46
  • http://stackoverflow.com/questions/134845/href-attribute-for-javascript-links-or-javascriptvoid0 – Tracker1 Nov 25 '14 at 22:48