控制器参数在使用jQuery POST和ASP.NET MVC时为NULL(Controller parameter NULL when using jQuery POST and ASP.NET M

编程入门 行业动态 更新时间:2024-10-17 02:57:50
控制器参数在使用jQuery POST和ASP.NET MVC时为NULL(Controller parameter NULL when using jQuery POST and ASP.NET MVC)

我在控制器中处理jQuery GET请求没有问题,但我无法获取任何表单数据到POST。 客户端片段

$.post(url,{name:"John"},function(result){ //process result });

结合控制器,

[AcceptVerbs(HttpVerbs.Post)] public ActionResult Save(string name) { return Json("Success!"); }

将在action方法内检查时为name参数生成一个NULL值,而我期望的名称将映射到方法参数。 其他所有对象(Request.Form)等在这个上下文中似乎都是NULL。 我可以用$.get做到这一点,但我认为我应该对POST做副作用的操作。 我正在使用ASP.NET MVC 1.0,jQuery 1.2.6和Internet Explorer 7。

谢谢!

更新 :请参阅下面的答案和谦卑的道歉

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

combined with a controller,

[AcceptVerbs(HttpVerbs.Post)] public ActionResult Save(string name) { return Json("Success!"); }

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.

Thanks!

Update: see my answer below and humble apologies

最满意答案

对不起,我在页面中有一个$ .ajaxSetup条目,它将默认的contentType重写为application / json。

如下所示使用默认的contentType时:

$.ajax({ url, type: "POST", contentType: "application/x-www-form-urlencoded", success: function(result) { alert(result); }, data: { name: "John" } });

它的工作原理是默认情况下processData为true,这意味着具有JSON对象的数据条目将被解析为一个字符串(data:“name = John”也可以)。

对不起,浪费你的时间:)并感谢Mark对传递JSON对象的建议,接下来的问题会导致它看起来很酷。

Sorry guys, I had a $.ajaxSetup entry in the page which overrided the default contentType to application/json.

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

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

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.

更多推荐

本文发布于:2023-08-01 22:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1365809.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   参数   POST   jQuery   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!