Calling ASP.NET MVC Action Methods from JavaScript

Javascriptasp.net Mvcasp.net Mvc-3Razor

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Use jQuery ajax:

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

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

Solution 2 - Javascript

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

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

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

Solution 5 - Javascript

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 6 - Javascript

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

Solution 7 - Javascript

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

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

Solution 8 - Javascript

You can set up your element with

value="@model.productId"

and

onclick= addToWishList(this.value);

Solution 9 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMilan MendparaView Question on Stackoverflow
Solution 1 - JavascriptPer KastmanView Answer on Stackoverflow
Solution 2 - JavascriptMurat YıldızView Answer on Stackoverflow
Solution 3 - JavascriptShyjuView Answer on Stackoverflow
Solution 4 - JavascriptSaeed NeamatiView Answer on Stackoverflow
Solution 5 - JavascriptarchilView Answer on Stackoverflow
Solution 6 - JavascriptJabulani VilakaziView Answer on Stackoverflow
Solution 7 - JavascriptDeshani TharakaView Answer on Stackoverflow
Solution 8 - JavascriptAmmarView Answer on Stackoverflow
Solution 9 - JavascriptAhmed AlshubakyView Answer on Stackoverflow