[javascript] 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?

This question is related to javascript asp.net-mvc asp.net-mvc-3 razor

The answer is


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.


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


You can simply add this when you are using same controller to redirect

var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;

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")';
    });
});

You can set up your element with

value="@model.productId"

and

onclick= addToWishList(this.value);


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


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);
  }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC