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?
The Controller's Action method is called using JavaScript XmlHttpRequest (XHR) AJAX request and the value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.
Use jQuery ajax:
function AddToCart(id) { $.ajax({ url: 'urlToController', data: { id: id } }).done(function() { alert('Added'); }); }
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter window.location.href = '@Url.Action("Action", "Controller")/' + id;
Hope this helps...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With