Reputation: 3
consider the function
public JsonResult poststuff()
{
var form = Request.Form;
return new JsonResult() { Data = form };
}
consider the submitted data (JSON)
{
name: "John Doe",
age: "50"
}
This is my question
Is there any way to return the post data as a JSON? Without having to pull the data apart and insert it into an object of an type?
I feel like i've been trawling the web for an answer but has not been able to find one ... and know i turn to you.
The returndata would be prefered as the following:
{ data: { name: "John Doe", age: 50 } } or even better { name: "John Doe", age: 50 }
Is it even possible to do it in a simple way? I know it is i PHP but i've never succeeded in finding an answer in C# .NET
As a reference, the wished result can be created in PHP as easy as
$input_data = json_decode(trim(file_get_contents('php://input')), true);
echo json_encode($input_data);
Upvotes: 0
Views: 4569
Reputation: 9458
If you are using form to post the data, then you can use the [FormCollection][1]
class as below:
[HttpPost]
public ActionResult PostStuff(FormCollection formCollection)
{
Dictionary<string, string> data = new Dictionary<string, string>();
//If data is POSTed as a form
foreach (var key in formCollection.AllKeys)
{
var value = formCollection[key];
data.Add(key, value);
}
return Json(data, "application/json", JsonRequestBehavior.AllowGet);
}
Here, we are just looping through the collection POSTed from the form and adding it to the dictionary. This dictionary is then passed to JsonResult
.
Upvotes: 1