I have the following script that is sending data to a controller in MVC:
$.ajax({
url: '/products/create',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'name':'widget',
'foo':'bar'
})
});
My controller looks like this:
[HttpPost]
public ActionResult Create(Product product)
{
return Json(new {success = true});
}
public class Product
{
public string name { get; set; }
}
Is there a way I can get the "foo" variable in my controller action without
If it was a regular form submission, I would have access to Request.Form["foo"], but this value is null since it was submitted via application/json.
I want to be able to access this value from an Action Filter and that is why I don't want to modify the signature/model.
I wanted to do almost exactly the same today and found this question with no answer. I also solved it with similar solution as Mark.
This works very well for me in asp.net MVC 4. Could maybe help someone else reading this question even if it is an old one.
[HttpPost]
public ActionResult Create()
{
string jsonPostData;
using (var stream = Request.InputStream)
{
stream.Position = 0;
using (var reader = new System.IO.StreamReader(stream))
{
jsonPostData = reader.ReadToEnd();
}
}
var foo = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonPostData)["foo"];
return Json(new { success = true });
}
The important part was to reset the position of the stream because it is already read by some MVC internal code or whatever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With