2017-07-16 143 views
-4

如果輸入變量(a)未設置爲Null,則以下Ajax代碼甚至不會觸發我的操作。Ajax爲什麼不發送數據?

Ajax代碼:

var ab = "Chocolate Smoothies ya know?"; 

$("#customerSubmit").submit(function (e) { 

    e.preventDefault(); 

    $.ajax({ 
     url: "/api/Booking/lander", 
     method: "post", 
     data: { a: ab } 
    }) 
}); 

下面我控制器代碼:

[HttpPost] 
public void lander(string a) 
{ 
    System.Diagnostics.Debug.WriteLine(a); 
} 

當我不將它設置爲空,接收到的輸入爲空。

截圖時觸發斷點:

enter image description here

我用類型/方法/等似乎沒有任何工作

更新:

我甚至嘗試以下但沒有用:

更新2:

即使以下沒有工作,下列情況之一也給了我 - >「無法加載資源:服務器與405狀態(不允許的方法)迴應」

var ab = 'Chocolate Smoothies ya Know?'; 
$.ajax({ 
    url:"/api/Booking/lander", 
    data: {'': ab} 
}); 

隨着

public string lander([FromUri]string asx) ////and asx = "" and /// asx = null 

enter image description here

enter image description here

更新3

事情非常奇怪的事情,我用下面的代碼:

enter image description here enter image description here

,我得到了以下錯誤:

enter image description here

,當我用

////(string a = "")

它triggere我的行動出於某種未知的原因,發生了以下事情。

enter image description here

以下是我的WebApiConfig代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 

namespace HotelManagementSystem 
{ 
    public static class WebApiConfig 
    { 
     public static void Register(HttpConfiguration config) 
     { 
      config.MapHttpAttributeRoutes(); 

      //routes.MapHttpRoute("RestApiRoute", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" }); //this replaces your current api route 


      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{action}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 
     } 
    } 
} 

更新4:

即使下面設置沒有工作:

enter image description here

enter image description here

enter image description here

回答

0

您需要設置contentTypestringify要發送到控制器的數據。所以,你會發送數據將是:

var postData = JSON.stringify({'a':ab}); 

所以生成的代碼應該是這樣的:

var ab = 'Chocolate Smoothies ya Know?'; 
var postData = JSON.stringify({'a':ab}); 
$.ajax({ 
    url: "/api/Booking/lander", 
    method: "POST", 
    contentType: "application/json", 
    data: postData 
}); 

您可以選擇要設置dataType: "json"了。您不需要在lander方法中指定a參數的任何查找位置(uri,body)。

+1

它沒有工作.... –

+0

@derloopkat我看,所以你有什麼建議? –

+0

@derloopkat'@'使用(Html.BeginForm(「AddCustomer」,「api/Booking」,FormMethod.Post,new {id =「customerSubmit」})){} –

0

你有你的RouteConfig.cs定義了默認路由文件

routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
      namespaces: new [] { "YourNameSpace.Controllers" } 
     ); 

如果你改變「一」在您的簽名爲「ID」,並通過你的Ajax發送「ID」你一定會成功,但如果你希望在你的post方法中有多個參數,或者不同的命名嘗試定義新的路由。

+0

在她的第一張截圖中,您可以看到方法運行 – derloopkat

+0

@derloopkat當然是的,但由於MVC中路由的使用不當,參數爲空。 –

+0

MapRoute是一個mvc控制器,而她有一個webapi。語法是不同的,這個代碼不會在那裏編譯。另一方面,我沒有看到任何可選參數不會被找到的原因。添加stringify和contenttype後,她的代碼適用於我。我想刪除我的答案,因爲我認爲Nicosoften的答案應該足夠了。 – derloopkat

相關問題