使用jQuery POST和ASP.NET MVC时,Controller参数为NULL [英] Controller parameter NULL when using jQuery POST and ASP.NET MVC
问题描述
我在控制器中处理jQuery GET请求没有问题,但我无法获取任何表单数据到POST。客户端代码段
I have no problems processing jQuery GET requests in a controller, however I cannot get any form data to POST. The client snippet
$.post(url,{name:"John"},function(result){
//process result
});
与控制器相结合,
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(string name)
{
return Json("Success!");
}
在操作方法中检查时将导致name参数为NULL值,而我希望将名称映射到方法参数。此外,此上下文中的所有其他对象(Request.Form)等似乎都是NULL。我可以用 $。get
来做到这一点,但我想我应该做任何带有POST副作用的操作。我正在使用ASP.NET MVC 1.0,jQuery 1.2.6和Internet Explorer 7.
will result in a NULL value for the name parameter when inspected inside the action method, whereas I expected name to be mapped to the method parameter. Also all other objects (Request.Form), etc. in this context seem to be NULL. I can do this with a $.get
, but I think I am supposed to do any operations with side-effects with POSTs. I am using ASP.NET MVC 1.0, jQuery 1.2.6 and Internet Explorer 7.
谢谢!
更新:请参阅下面的答案和谦虚的道歉
Update: see my answer below and humble apologies
推荐答案
很抱歉,我在页面中有一个$ .ajaxSetup条目,它将默认的contentType覆盖为application / json。
Sorry guys, I had a $.ajaxSetup entry in the page which overrided the default contentType to application/json.
当使用默认的contentType作为如下:
When using the default contentType as follows:
$.ajax({ url,
type: "POST",
contentType: "application/x-www-form-urlencoded",
success: function(result) { alert(result); },
data: { name: "John" }
});
它的工作原理是因为默认情况下processData为true,这意味着带有JSON对象的数据条目将被解析为一个字符串(数据:name = John也有效)。
It works because processData is true by default which means the data entry with the JSON object will be parsed into a string (data: "name=John" also works).
很抱歉浪费你的时间:)并感谢Mark关于传递JSON对象的建议,生病了那下一个原因看起来很酷。
Sorry for wasting your time :) and thanks to Mark for the suggestion on passing JSON objects, ill do that next cause it seems very cool.
这篇关于使用jQuery POST和ASP.NET MVC时,Controller参数为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!