Calling ASP.NET MVC Action Methods from JavaScript

I have an example code:

<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 to write JavaScript code to call a controller action method?

+45
javascript asp.net-mvc asp.net-mvc-3 razor
Jan 21 '12 at 12:26
source share
8 answers

Use jQuery ajax:

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

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

+49
Jan 21 2018-12-12T00:
source share

You call the addToCart method and pass in the product identifier. Now you can use jQuery ajax to pass this data to your server side action method. D

jQuery post is a short version of jQuery ajax.

 function addToCart(id) { $.post('@Url.Action("Add","Cart")',{id:id } function(data) { //do whatever with the result. }); } 

If you need other parameters like 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 highly 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 razor mode because Url.Action will be executed by the razor on the server side and that the C # expression will be replaced with the correct relative path. But if you use jQuery code in your external js file, you can consider the approach mentioned in this.

+10
Jan 21 '12 at 14:45
source share

If you do not need a lot of customization and you are looking for simplicity, you can do it with the built-in method - AjaxExtensions.ActionLink method .

 <div class="cart"> @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" }); </div> 

This MSDN link is required for all possible overloads of this method and parameters of the AjaxOptions class . In fact, you can use confirmation, change the http method, set the scripts of OnSuccess and OnFailure clients, etc.

+10
Jan 21 2018-12-18T00:
source share

You can simply call the Action Method through Javascript as follows:

 var id = model.Id; //if you want to pass an Id parameter window.location.href = '@Url.Action("Action", "Controller")/' + id; 

Hope this helps ...

+10
Dec 16 '15 at 11:00
source share

If you want to trigger an action from within your JavaScript, one way is to embed your JavaScript code inside your view (for example, a .cshtml file), and then use Razor to create the URL for this action:

 $(function(){ $('#sampleDiv').click(function(){ /* While this code is JavaScript, but because it 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")'; }); }); 
+9
Jan 21 2018-12-12T00:
source share

You can simply add this when using the same controller to redirect

 var url = "YourActionName?parameterName=" + parameterValue; window.location.href = url; 
+3
Oct. 20 '16 at 10:28
source share

You can customize element with

value="@model.productId"

and

onclick= addToWishList(this.value);

0
Sep 06
source share
 Javascript Function function AddToCart(id) { $.ajax({ url: '@Url.Action("AddToCart", "ControllerName")', type: 'GET', dataType: 'json', cache: false, data: { 'id': id }, success: function (results) { alert(results) }, error: function () { alert('Error occured'); } }); } Controller Method to call [HttpGet] public JsonResult AddToCart(string id) { string newId = id; return Json(newId, JsonRequestBehavior.AllowGet); } 
0
Jan 04 '16 at 9:16
source share



All Articles