通过ajax将表单数据发送到webapi

本文关键字:webapi 数据 ajax 表单 通过 | 更新日期: 2023-09-27 17:52:34

我希望post formdata到c# web api,并有模型绑定工作。这看起来应该是可能的,但是我的对象从来没有被填充。我想保持代码的简单和灵活。ie。我不想添加一个新的json属性到我的ajax调用每次我添加一个新的表单字段,我想传递文件,如果我希望(不期望文件绑定到模型)。

这是我目前的基本资料。

$('.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);
        }
    });
});

在我的控制器

public int Insert([FromBody] Plant plant)
{
    return plant.Insert();
}

和我的模型

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() { }
}

和样本数据

------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--

结果是植物实例不为空,但所有属性都为空,因此在数据库中插入了一个空行。是我要求太多了,还是我做错了?

通过ajax将表单数据发送到webapi

我会使用fiddler来测试post到服务URL,但你发布的数据应该是json格式,我很确定:

{ plant_id: 1, live: true, genius: "test genius", ... }

作为POST数据发送的new FormData($('form')[0])的输出是什么?

根据这个答案,我相信您需要做这样的事情:

$('.save').click(function () {
    var fd = new FormData();    
    fd.append( 'name', $('form')[0] );
    $.ajax({
        url: 'api/plant/insert',
        data: fd,
        type: 'POST',
        processData: false,
        contentType: false,
        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);
        }
    });
});