Reputation: 11597
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.
Upvotes: 1
Views: 2759
Reputation: 2523
Your ajax call content/type is text/html, you need to specify to your controller that you are sending application/json information, otherwise he receives the info, but doesn't know how to distribute it to it's params
Upvotes: 1