2017-07-16 142 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

相关问题