Calling ASP.NET MVC Action Methods from JavaScript
Solution 1
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Solution 2
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...
Solution 3
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.
function addToCart(id)
{
$.post('@Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '@Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
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.
Solution 4
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
@Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
Solution 5
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:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '@Url.Action("ActionName", "Controller")';
});
});
Milan Mendpara
A die hard OwlCity fan who also loves programming, photography and oil painting. It's always great to be a part of stack community. Catch me on appledelegate [at] yahoo [dot] com
Updated on November 16, 2021Comments
-
Milan Mendpara over 2 years
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?
-
Sterno about 11 yearsThere is a syntax error with the example above, as there should be a comma after data: { id: id }, but unfortunately it is deemed too trivial an edit for me to fix.
-
DigitalNomad almost 11 years@Sterno I queued it up for a peer review. Thanks for leaving your post; it sped up my troubleshooting process.
-
Zia Ul Rehman Mughal about 8 yearsANy suggestion for using this kind of code in .js file?
-
Deshani Tharaka about 6 yearsYou can use a different controller also,
var url = "YourController/YourActionName?parameterName=" + parameterValue; window.location.href = url;
-
Scott Fraley about 5 yearsUnfortunately (unless I'm way off here), this will require that you have the JavaScript WITHIN the .cshtml file. Personally, I definitely prefer my js in its own file.
-
EthernalHusky over 4 yearsThis is a brillant solution. I always use JS inside all my .cshtml files because it is a good practice to include in it.
-
Web Developer about 3 yearsWhat should I type in by url, the complete url, or just the action & controller?
-
Per Kastman almost 3 yearsThe complete URL.
-
dellos over 2 years@MuratYildiz; Can I set Post or Get ?
-
Murat Yıldız over 2 years@dellos I only used for GET, but both should be ok.
-
Daniel King over 2 yearsI had to remove the forward slash to make this work: window.location.href = '@Url.Action("Action", "Controller")' + id;