[c#-4.0] 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.

This question is related to c#-4.0 jquery asp.net-mvc-4 asp.net-web-api

The answer is


I believe you need quotes around the model:

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

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


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


Examples related to c#-4.0

Xml Parsing in C# EPPlus - Read Excel Table How to add and get Header values in WebApi How to make all controls resize accordingly proportionally when window is maximized? How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project How to get first record in each group using Linq How to get first object out from List<Object> using Linq ASP.Net MVC - Read File from HttpPostedFileBase without save .NET NewtonSoft JSON deserialize map to a different property name Datetime in C# add days

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?

Examples related to asp.net-web-api

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located