Ajax Post数据在服务器方法上无效

时间:2017-05-25 07:54:58

标签: jquery ajax asp.net-mvc

我有这个ajax电话;

var insertOrUpdate = function (url, callback, data) {
        $.post(url, data, callback);
    }

,数据是;

{"Companies":[],"HoldingCompanyId":3,"VatRegistrationNumber":"321-3123-45","Name":"gkjhgasdg g jghasfk jg","Created":"2017-05-23T00:00:00","CreatedBy":12,"LastModified":null,"LastModifiedBy":0}

我的控制器上有;

public ActionResult InsertOrUpdate(HoldingCompany holdingCompany)
{
    ...
}

其中HoldingCompany定义为;

    public class HoldingCompany : IHoldingCompany, IAuditInfoCreated, IAuditInfoModified
    {
        [Key]
        public int HoldingCompanyId { get; set; }

        public string VatRegistrationNumber { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Company> Companies { get; set; }
        public DateTime Created { get; set; }
        public int CreatedBy { get; set; }
        public DateTime? LastModified { get; set; }
        public int LastModifiedBy { get; set; }
    }
}

然而,当发布数据时,所有字段都设置为空值或默认值。那是为什么?

1 个答案:

答案 0 :(得分:3)

您可能需要设置Content-Type请求标头:

var insertOrUpdate = function (url, callback, data) {
    $.ajax({
        url: url,
        method: "POST",
        contentType: "application/json",
        data: JSON.stringify(data), 
        success: callback
    });
};

我已在JSON.stringify变量上应用了data,但只有在您的问题中显示的是javascript对象时才需要这样做。如果它是一个字符串,那么你不需要对其进行字符串化。