I'm new to asp.net mvc. I'm having some trouble getting the values of parameters in my Action methods.
I have the following code:
[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();
}
I access this method using an Ajax request. The request has these headers:
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
and this body:
mode=off
My problem is that the mode
parameter of ToggleRecommend
is not being populated with the value from the request - instead, it is null.
The request is reaching my server correctly: the variable content
in the method has the value mode=off
and Request.ContentLength
is 8 as expected. Also, Request.RequestType
is "POST", as is intended. However, Request.Form
is empty: it has no keys or values. (I don't know if that is relevant).
What is going wrong here? How do I get the value of my mode
parameter to go into my action method?
The problem must be to do with post: If I remove the HttpPost
attribute and do a request to the Url localhost:62718/microsite/toggleRecommend/?mode=off
the mode
parameter gets the value off
as is intended.
Edit:
The request is being made with javascript using the Mootools library. I've included that part of the code below:
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'} });
Using firebug, I can see the exact format of the request (and that looks fine) so hopefully the specifics of the javascript code doesn't matter.
您的ajax呼叫内容/类型为text / html,您需要向控制器指定您正在发送应用程序/ json信息,否则他会收到该信息,但不知道如何将其分发到它的params
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.