70

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Milan Mendpara
  • 3,091
  • 4
  • 40
  • 60

10 Answers10

79

Use jQuery ajax:

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

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

Community
  • 1
  • 1
Per Kastman
  • 4,466
  • 24
  • 21
32

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;
Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63
15

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.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
11

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")';
    });
});
Community
  • 1
  • 1
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
11

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

archil
  • 39,013
  • 7
  • 65
  • 82
5
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);
  }
5

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

var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
Deshani Tharaka
  • 183
  • 4
  • 14
  • 1
    You can use a different controller also, `var url = "YourController/YourActionName?parameterName=" + parameterValue; window.location.href = url;` – Deshani Tharaka Mar 06 '18 at 11:16
1

You can set up your element with

value="@model.productId"

and

onclick= addToWishList(this.value);

Ammar
  • 1,068
  • 2
  • 13
  • 20
1

I am using this way, and worked perfectly:

//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
    var formdata = new FormData(); //FormData object
    //Iterating through each files selected in fileInput
    formdata.append("username", username);
    formdata.append("phone", phone);
    formdata.append("email", email);
    formdata.append("code", code);
    formdata.append("filename", filename);

    //Creating an XMLHttpRequest and sending
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/InsertToDB');//controller/action
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
           //if success
        }
    }
}

in Controller:

public void InsertToDB(string username, string phone, string email, string code, string filename)
{
    //this.resumeRepository.Entity.Create(
    //    new Resume
    //    {
            
    //    }
    //    );
    var resume_results = Request.Form.Keys;
    resume_results.Add("");
}

you can find the keys (Request.Form.Keys), or use it directly from parameters.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

You can easily make a <a> link in your view.

<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>

then in you javascript code use this:

location.href = document.getElementById('link').href;
skr
  • 1,700
  • 1
  • 15
  • 39