【问题标题】:Can't pass a parameter with jquery to webapi post method from body无法将带有 jquery 的参数从正文传递给 webapi post 方法
【发布时间】:2019-03-20 09:39:49
【问题描述】:

我有一个运行良好的 webapi(用 rest 客户端测试)。我正在尝试使用 jQuery 调用 post 方法。

$.ajax$.post 方法发送的参数都是空的。

表单体传入的数据模型为:

public class SearchCandidatCriteria
{
    public string Nom;
    public string Sexe;
    public string Ville;
    public int SituationFamiliale;
    public int NiveauAcademique;
    public int ServiceNational;
    public string PosteDemande;
}

jQuery方法是:

$.ajax({
            'url': 'http://localhost:6232/api/Candidats/rechercher',
            'method': 'POST',
            'data': JSON.stringify('{"Nom":"","Sexe":"F","Ville":"","SituationFamiliale":0,"NiveauAcademique":";n,n,;n,;n","ServiceNational":"2","PosteDemande":"120"}'),
            'Content-Type': 'application/json',
            success : function(data) {
                console.log(data);
            }
        });

控制器接收到的参数始终为空

【问题讨论】:

    标签: jquery ajax post asp.net-web-api


    【解决方案1】:

    你构造的请求不正确

    构建 JavaScript 对象,然后将其字符串化

    var data = {Nom:"",Sexe:"F",Ville:"",SituationFamiliale:0,NiveauAcademique:";n,n,;n,;n",ServiceNational:"2",PosteDemande:"120"};
    $.ajax({
        url: 'http://localhost:6232/api/Candidats/rechercher',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success : function(data) {
            console.log(data);
        }
    });
    

    模型还应该使用属性而不是字段

    public class SearchCandidatCriteria {
        public string Nom { get; set; }
        public string Sexe { get; set; }
        public string Ville { get; set; }
        public int SituationFamiliale { get; set; }
        public int NiveauAcademique { get; set; }
        public int ServiceNational { get; set; }
        public string PosteDemande { get; set; }
    }
    

    【讨论】:

    • 谢谢@nkosi。我的代码中有两个错误:1. 使用 ajax 构建数据集的 worg 以及 (2) 我的类中缺少 getter 和 setter。
    • @alisriti 是的,这是对所犯错误的准确评估。
    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多