Skip to content
Advertisement

Calling ASP.NET MVC Action Methods from JavaScript

I have sample code like this:

 <div class="cart">
      <a onclick="addToCart('@Model.productId');" class="button"><span>Add to Cart</span></a>
 </div>
 <div class="wishlist">
      <a onclick="addToWishList('@Model.productId');">Add to Wish List</a>
 </div>
 <div class="compare">
      <a onclick="addToCompare('@Model.productId');">Add to Compare</a>
 </div>    

How can I write JavaScript code to call the controller action method?

Advertisement

Answer

Use jQuery ajax:

function AddToCart(id)
{
   $.ajax({
      url: 'urlToController',
      data: { id: id }
   }).done(function() {
      alert('Added'); 
   });
}

http://api.jquery.com/jQuery.ajax/

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement