添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams
 <div class="cart">
      <a onclick="addToCart('@Model.productId');" class="button"><span>Add to Cart</span></a>
 <div class="wishlist">
      <a onclick="addToWishList('@Model.productId');">Add to Wish List</a>
 <div class="compare">
      <a onclick="addToCompare('@Model.productId');">Add to Compare</a>

How can I write JavaScript code to call the controller action method?

There 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. – Sterno Apr 9, 2013 at 17:38 @Sterno I queued it up for a peer review. Thanks for leaving your post; it sped up my troubleshooting process. – DigitalNomad May 22, 2013 at 3:10

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;
                Unfortunately (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.
– Scott Fraley
                May 9, 2019 at 20:59
                This is a brillant solution. I always use JS inside all my .cshtml files because it is a good practice to include in it.
– EthernalHusky
                Jan 14, 2020 at 0:26
                I had to remove the forward slash to make this work:  window.location.href = '@Url.Action("Action", "Controller")' + id;
– Daniel King
                Jan 19, 2022 at 18:40

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

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

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 simply add this when you are using same controller to redirect

var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
                You can use a different controller also, var url = "YourController/YourActionName?parameterName=" + parameterValue; window.location.href = url;
– Deshani Tharaka
                Mar 6, 2018 at 11:16

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.

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;
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.