Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending JSON object to Web API

I am trying to figure out how I can send some information from a form to a Web API action. This is the jQuery/AJAX I'm trying to use:

var source = { 
        'ID': 0, 
        'ProductID': $('#ID').val(), 
        'PartNumber': $('#part-number').val(),
        'VendorID': $('#Vendors').val()
    }

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/api/PartSourceAPI/",
        data: JSON.stringify({ model: source }),
        success: function (data) {
            alert('success');
        },
        error: function (error) {
            jsonValue = jQuery.parseJSON(error.responseText);
            jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
        }
    });

Here is my model

public class PartSourceModel
{
    public int ID { get; set; }
    public int ProductID { get; set; }
    public int VendorID { get; set; }
    public string PartNumber { get; set; }
}

Here is my view

<div id="part-sources">
    @foreach (SmallHorse.ProductSource source in Model.Sources)
    {
        @source.ItemNumber <br />
    }
</div>
<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />

<input type="submit" id="save-source" name="save-source" value="Add" />

Here is my controller action

// POST api/partsourceapi
public void Post(PartSourceModel model)
{
    // currently no values are being passed into model param
}

What am I missing? right now when I debug and step through this when the ajax request hits the controller action there is nothing being passed into the model param.

like image 398
Cory Avatar asked Dec 13 '12 23:12

Cory


People also ask

How do I send data to REST API?

Use an HTTP POST request to send single or multiple RPC requests to the REST API. You can use the POST request to do device configuration. method : The name of any Junos OS rpc command. The method name is identical to the tag element.

Can you use JSON with REST API?

The REST architecture allows API providers to deliver data in multiple formats such as plain text, HTML, XML, YAML, and JSON, which is one of its most loved features.

How to send JSON in HTTP GET with angular and web API?

Send JSON in http Get with angular and Web Api. First prepare URLSearchParams object and add key value pairs. Send the RequestOptions to Angular http service. Your server side ViewModel matches your JSON object sent in the request.

How to send JSON data to a class object?

You need to use JSON.stringify method to convert it to JSON string when you send it, And the model binder will bind the json data to your class object.

Can I send multiple JSON objects in an HTTP request?

In principle, you can send any content in HTTP request, it only need to be serializable into a string. So, it could be multiple JSON object. I don't even understand where you could get stuck.

How do I deserialize a JSON object from a client request?

If your web API receives loosely structured JSON objects from clients, you can deserialize the request body to a Newtonsoft.Json.Linq.JObject type. However, it is usually better to use strongly typed data objects. Then you don't need to parse the data yourself, and you get the benefits of model validation.


3 Answers

Try this:

jquery

    $('#save-source').click(function (e) {
        e.preventDefault();
        var source = {
            'ID': 0,
            //'ProductID': $('#ID').val(),
            'PartNumber': $('#part-number').val(),
            //'VendorID': $('#Vendors').val()
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/api/PartSourceAPI",
            data: source,
            success: function (data) {
                alert(data);
            },
            error: function (error) {
                jsonValue = jQuery.parseJSON(error.responseText);
                //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
            }
        });
    });

Controller

    public string Post(PartSourceModel model)
    {
        return model.PartNumber;
    }

View

<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />

<input type="submit" id="save-source" name="save-source" value="Add" />

Now when you click 'Add' after you fill out the text box, the controller will spit back out what you wrote in the PartNumber box in an alert.

like image 87
mnsr Avatar answered Oct 24 '22 06:10

mnsr


Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

like image 6
Jeroen Avatar answered Oct 24 '22 06:10

Jeroen


var model = JSON.stringify({ 
    'ID': 0, 
    'ProductID': $('#ID').val(), 
    'PartNumber': $('#part-number').val(),
    'VendorID': $('#Vendors').val()
})

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "/api/PartSourceAPI/",
    data: model,
    success: function (data) {
        alert('success');
    },
    error: function (error) {
        jsonValue = jQuery.parseJSON(error.responseText);
        jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
    }
});

var model = JSON.stringify({      'ID': 0,     ...': 5,      'PartNumber': 6,     'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"

your data is something like this "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api controller cannot bind it to Your model

like image 3
Ashot Avatar answered Oct 24 '22 07:10

Ashot