I'm looking to post formdata to a c# web api and have the model binding work. This looks like it should be possible, but my object is never populated. I want to keep the code simple and flexible. ie. i dont want to add a new json attribute to my ajax call every time i add a new form field and i would like to pass files if i wish to (not expecting files to bind to the model).
Here is basically what I have at the moment.
$('.save').click(function () {
$.ajax({
url: 'api/plant/insert',
data: new FormData($('form')[0]),
type: 'POST',
processData: false,
contentType: 'application/x-www-form-urlencoded',
beforeSend: function () {
$.processing({ content: 'Saving Plant' });
},
error: function () {
$.error({ content: 'An error occurred saving the plant' });
},
success: function (data) {
location.assign('PlantEdit.cshtml?plant_id=' + data);
}
});
});
and in my controller
public int Insert([FromBody] Plant plant)
{
return plant.Insert();
}
and my model
public class Plant : Data
{
public int plant_id { get; set; }
public bool live { get; set; }
public string genus { get; set; }
public string species { get; set; }
public string variety_name { get; set; }
public Plant() { }
}
and sample post data
------WebKitFormBoundaryc6x6E9JewE0ln4ql
Content-Disposition: form-data; name="live"
on
------WebKitFormBoundaryc6x6E9JewE0ln4ql
Content-Disposition: form-data; name="genus"
test genus name
------WebKitFormBoundaryc6x6E9JewE0ln4ql
Content-Disposition: form-data; name="species"
test species name
------WebKitFormBoundaryc6x6E9JewE0ln4ql
Content-Disposition: form-data; name="variety_name"
test variety name
------WebKitFormBoundaryc6x6E9JewE0ln4ql--
The result is the plant instance is not null, but all attributes are null, hence an empty row inserted into the database. So am I asking for too much, or am I going about this all wrong?