简体   繁体   中英

Returning post data as JSON

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);

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM