Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 626
Milan Mendpara Avatar asked Jan 21 '12 12:01

Milan Mendpara


People also ask

How do you call an action method in JavaScript?

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.

Can ASP NET MVC use JavaScript?

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.


2 Answers

Use jQuery ajax:

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

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

like image 180
Per Kastman Avatar answered Oct 12 '22 12:10

Per Kastman


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...

like image 41
Murat Yıldız Avatar answered Oct 12 '22 14:10

Murat Yıldız