appsecguy appsecguy -4 years ago 96
C# Question

Use JSON to post a collection of models to webapi

Here is my situation. I built a web service that is designed to populate a report. It receives a variable number of "findings" and then generates a report containing all of the findings.

Is there a way to post, using JSON, multiple findings at once, and have it bind to a List object?

EDIT:

So to be more specific, a finding would look like:

{ title: "title", description: "desc", rating: "High"}

I would like to be able to have my function look like this:

[HttpPost]
public string Post(IList<Finding> findings){
//code...
}

public class Finding{
public string title {get; set;}
//...
}


So essentially I want to bind an array of those JSON findings into an IList

UPDATE:
I am looking to be able to have it bind automatically. I am currently able to workaround by posting a JSON string (using JSON.stringify)

Here is my code that works:

[HttpPost]
public string Post([FromBody]object jsonString){
IList<Finding> findingList = JsonConvert.DeserializeObject<IList<Finding>>(jsonString.toString());
//...
}


Any idea on how to get this to bind automatically, rather than having to convert?

Answer Source

if you stay with your solution :

[HttpPost]
public string Post([FromBody]object jsonString){
IList<Finding> findingList = JsonConvert.DeserializeObject<IList<Finding>>     (jsonString.toString());
//...
}

i think that you can :

[HttpPost]
public string Post(string jsonString){
IList<Finding> findingList = JsonConvert.DeserializeObject<IList<Finding>>     (jsonString);
//...
}

...And in your ajax call :

    $.ajax({
    ...
    data: JSON.Stringify(data),
    ...
    });

OR,

you can try something like (it comes from my code) :

    var LoginFormSubmitHandler = function (e) {
    var $form = $(this);
    // We check if jQuery.validator exists on the form
    if (!$form.valid || $form.valid()) {

        $.post($form.attr('action'), $form.serializeArray())
        ...

...and can you show the value of $form.serializeArray() ??

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download