2016-12-30 124 views
0

我已经发布数据到我的MVC控制器没有问题(使用ajax后和HttpPost)。为什么不提供任何参数

我遇到的问题是,它是异步的,我需要它发布并等待响应。

因此,有get

然而,当我这样做,从来就没有传递参数。

我的JavaScript

//the type is "GET" 
function toDatabase(type, url, data, successDelegate, failDelegate, errorDelegate) { 
    $.ajax({ 
     type: type.toUpperCase(), 
     url: url, 
     contentType: "application/json;", 
     data: data, 
     dataType: "json", 
     success: function (response) { 
      successDelegate(response); removeSpinner(); 
     }, 
     failure: function (e) { 
      failDelegate(e.statusText); removeSpinner(); 
     }, 
     error: function (e) { 
      errorDelegate(e.statusText); removeSpinner(); 
     } 
    }) 
} 

和我的控制器是

[HttpGet] 
public JsonResult SaveNewStagePlan(string name) 
{ 
    //todo save 
    if (String.IsNullOrEmpty(name)) 
     return Json(new { id = -99 }); //always returns as name is null 
} 

我做了什么错?它在发布(并使用HttpPost)时运行良好。

编辑

数据的值是{"name":"MyBand"},通过该传递JSON.stringify({ 'name': localVariableBandName })

+0

你的'toDatabase'方法'data'参数中传递的值是什么? – Shyju

+0

@Shyju,我更新了我的帖子 – MyDaftQuestions

+0

你尝试过跳过'stringify'步骤吗?你没有在url参数中发送json ...如果你没有对它进行字符串化,那么在GET请求中使用'data'属性应该将url更改为'url?name = MyBand'。 – ps2goat

回答

1

JSON.stringify该方法需要一个js对象,并返回该对象的字符串化版本另一个函数创建。例如,如果您将js对象{ name: 'shyju' }传递给此方法,您将获得字符串{"name":"shyju"}

当ajax调用为GET类型时,数据将作为查询字符串值发送。 $.ajax方法将根据需要将您在data属性中传递的js对象转换为查询字符串键值对并发送它。

所以基本上你当前的代码发送查询字符串这样

Home/SaveNewStagePlan?{"name":"shyju"}` 

所以,你可以清楚地看到,这是不是一个有效的查询字符串!理想情况下它应该是Home/SaveNewStagePlan?name=shyju

因此,解决方案是将js对象原样传递给$.ajax调用(而不是对象的字符串化版本)。

这应该工作。

$.ajax({ 
    type: "GET", 
    url: url, 
    data: { name: 'shyju' }, 
    success: function(response) { 
     console.log(response); 
    }, 
    failure: function(e) { 
    }, 
    error: function(e) { 
    } 
}); 

既然是发送数据作为查询字符串,你并不需要指定contentType为“应用JSON”(它仍然会使用它虽然)。

此外,没有必要明确指定dataType作为json,因为您的代码总是返回json数据。

另外,如果您的操作方法是GET操作方法,则需要明确指定要从中返回JSON数据。您可以使用Json方法的超载,该方法采用JsonRequestBehavior枚举值。

return Json(new { id = -99 }, JsonRequestBehavior.AllowGet); 
+0

当我这样做,它击中我的控制器很好,但它总是返回到500状态的错误代表... :( – MyDaftQuestions

+0

您需要修复您的服务器代码。请参阅更新后的答案。 – Shyju

+0

OH CRUMBS ... I以前也使用过'allowget' :(谢谢(再次) – MyDaftQuestions

相关问题