从 JavaScript 调用 ASP.NET MVC 操作方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8952953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:12:18  来源:igfitidea点击:

Calling ASP.NET MVC Action Methods from JavaScript

javascriptasp.net-mvcasp.net-mvc-3razor

提问by Milan Mendpara

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 代码来调用控制器操作方法?

回答by KMan

Use jQuery ajax:

使用 jQuery ajax:

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

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

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

回答by Murat Y?ld?z

Simply call your Action Methodby using Javascriptas shown below:

只需使用Javascript调用您的操作方法,如下所示:

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

Hope this helps...

希望这可以帮助...

回答by Shyju

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

您正在调用 addToCart 方法并传递产品 ID。现在您可以使用 jQuery ajax 将该数据传递给您的服务器端操作 method.d

jQuery post is the short version of jQuery ajax.

jQuery post 是 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,

如果您想要更多选项,例如成功回调和错误处理,请使用 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.Actionto generate the path to your action methods.

在进行 ajax 调用时,我强烈建议使用 Html 辅助方法,例如Url.Action生成操作方法的路径。

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.

如果您的代码在 razor 视图中,这将起作用,因为 Url.Action 将由服务器端的 razor 执行,并且该 c# 表达式将替换为正确的相对路径。但是,如果您在外部 js 文件中使用 jQuery 代码,则可以考虑此答案中提到的方法。

回答by archil

If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.

如果您不需要太多的自定义并追求简单,您可以使用内置方式 - AjaxExtensions.ActionLink 方法来实现

<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

对于此方法的所有可能重载和AjaxOptions 类的参数,必须阅读该 MSDN 链接。实际上,您可以使用确认、更改 http 方法、设置 OnSuccess 和 OnFailure 客户端脚本等

回答by Saeed Neamati

If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtmlfile for example), and then, use Razor, to create a URL of that action:

如果要从 JavaScript 调用操作,一种方法是将 JavaScript 代码嵌入视图(.cshtml例如文件)中,然后使用 Razor 创建该操作的 URL:

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

回答by Deshani Tharaka

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

当您使用相同的控制器重定向时,您可以简单地添加它

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

回答by Jabulani Vilakazi

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

回答by Ammar

You can set up your elementwith

你可以设置你element

value="@model.productId"

value="@model.productId"

and

onclick= addToWishList(this.value);

onclick= addToWishList(this.value);