簡體   English   中英

從 JavaScript 調用 ASP.NET MVC 操作方法

[英]Calling ASP.NET MVC Action Methods from JavaScript

我有這樣的示例代碼:

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

如何編寫 JavaScript 代碼來調用控制器操作方法?

使用 jQuery ajax:

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

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

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

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

希望這可以幫助...

您正在調用 addToCart 方法並傳遞產品 ID。 現在您可以使用 jQuery ajax 將該數據傳遞給您的服務器端操作 method.d

jQuery post 是 jQuery ajax 的簡短版本。

function addToCart(id)
{
  $.post('@Url.Action("Add","Cart")',{id:id } function(data) {
    //do whatever with the result.
  });
}

如果您想要更多選項,例如成功回調和錯誤處理,請使用 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);

                }    
  });
}

在進行 ajax 調用時,我強烈建議使用諸如Url.Action之類的 Html 輔助方法來生成操作方法的路徑。

如果您的代碼在 razor 視圖中,這將起作用,因為 Url.Action 將由服務器端的 razor 執行,並且該 c# 表達式將替換為正確的相對路徑。 但是,如果您在外部 js 文件中使用 jQuery 代碼,您可以考慮這個答案中提到的方法。

如果你想從你的 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")';
    });
});

如果您不需要太多的自定義並尋求簡單性,您可以使用內置方式 - AjaxExtensions.ActionLink 方法來完成。

<div class="cart">
      @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>

對於此方法的所有可能重載和AjaxOptions 類的參數,必須閱讀該 MSDN 鏈接。 實際上,您可以使用確認、更改 http 方法、設置 OnSuccess 和 OnFailure 客戶端腳本等

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

當您使用相同的控制器進行重定向時,您可以簡單地添加它

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

你可以設置你的element

value="@model.productId"

onclick= addToWishList(this.value);

我正在使用這種方式,並且工作得很好:

//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
        }
    }
}

在控制器中:

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

您可以找到密鑰( Request.Form.Keys ),或直接從參數中使用它。

您可以輕松地在視圖中創建<a>鏈接。

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

然后在你的javascript代碼中使用這個:

location.href = document.getElementById('link').href;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM