ajax+post+webapi,c# - post formdata via ajax to webapi - Stack Overflow

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?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值