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?
Use jQuery ajax:
http://api.jquery.com/jQuery.ajax/
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (
.cshtml
file for example), and then, use Razor, to create a URL of that action:Hope this helps...
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
If you want more options like success callbacks and error handling, use jQuery ajax,
When making ajax calls, I strongly recommend using the Html helper method such as
Url.Action
to generate the path to your action methods.This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
You can set up your
element
withvalue="@model.productId"
and
onclick= addToWishList(this.value);