我是 asp.net mvc 的新手。我在获取 Action 方法中的参数值时遇到了一些问题。
我有以下代码:
[HttpPost]
public ActionResult ToggleRecommend(string mode)
{
byte[] requestContent = new byte[Request.ContentLength];
Request.InputStream.Read(requestContent, 0, Request.ContentLength);
string content = Encoding.ASCII.GetString(requestContent);
return EmptyResult();
}
我使用 Ajax 请求访问此方法。该请求具有以下 header :
Accept application/json
Accept-Encoding gzip, deflate
Accept-Language en-gb,en;q=0.5
Connection keep-alive
Content-Length 8
Content-Type text/plain; charset=UTF-8
Host localhost:62718
Referer http://localhost:62718/microsite
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1
X-Request JSON
X-Requested-With XMLHttpRequest
还有这个 body :
mode=off
我的问题是 ToggleRecommend
的 mode
参数没有填充请求中的值 - 相反,它为 null。
请求正确到达我的服务器:方法中的变量 content
的值为 mode=off
并且 Request.ContentLength
为 8正如预期的那样。此外,Request.RequestType
是预期的“POST”。但是,Request.Form
是空的:它没有键或值。 (我不知道这是否相关)。
这里出了什么问题?如何获取我的 mode
参数的值以进入我的操作方法?
问题一定与帖子有关:如果我删除 HttpPost
属性并对 Url localhost:62718/microsite/toggleRecommend/?mode=off
mode
参数按预期获得值 off
。
编辑:
请求是通过使用 Mootools 库的 javascript 发出的。我已经包含了下面的那部分代码:
var req = new Request.JSON({ method: "post",
url: "/microsite/toggleRecommend/" ,
autoCancel: true, urlEncoded: false, secure: false,
onFailure: recommendFail, onException: recommendFail,
onSuccess: recommendSuccess
});
req.send({ data: { mode: 'on'} });
使用 firebug,我可以看到请求的确切格式(看起来不错),所以希望 javascript 代码的细节无关紧要。
最佳答案
你的 ajax 调用内容/类型是 text/html,你需要向你的 Controller 指定你正在发送 application/json 信息,否则他会收到信息,但不知道如何将它分发给它的参数
关于c# - 将 post 参数传递给 asp.net mvc 中的操作方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12712199/