ASP.NET MVC后端控制器用模型 接收前端ajax数据为空

1、前端js代码

如下:

javascript 复制代码
const formData = {
    DeptName: 'D001',
    Phone: '12345678900'
};

$.ajax({
    url: "/Phone/SavePhone1",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(formData), //必须要JSON.stringify
    success: function (result) {
        if (result > 0) {
            alert("保存成功!")
        }
        else {
            alert("保存失败!")
        }
    },
    error: function (xhr, status, error) {
        alert("操作失败:" + error);
    }
});

2、问题描述

直接使用DeptPhone模型接收,接收不到数据,使用[FromBody]也不行:

3、解决方案

改用Request.InputStream来获取数据,然后使用JsonConvert来转换成实体,代码如下:

cs 复制代码
public int SavePhone()
{
    // 用模型接收不了ajax传过来的json数据,使用Request.InputStream获取
    var phone = Newtonsoft.Json.JsonConvert.DeserializeObject<DeptPhone>(new StreamReader(Request.InputStream).ReadToEnd());
    int result = _deptPhone.SavePhone(phone);
    return result;
}
相关推荐
智商偏低4 天前
ASP.NET Core 中的简单授权
后端·asp.net
是萝卜干呀6 天前
IIS 部署 asp.net core 项目时,出现500.19、500.31问题的解决方案
后端·iis·asp.net·hosting bundle
速易达网络8 天前
ASP.NET MVC 连接 MySQL 数据库查询示例
数据库·asp.net·mvc
智商偏低8 天前
ASP.NET Core 身份验证概述
后端·asp.net
冷冷的菜哥8 天前
ASP.NET Core使用MailKit发送邮件
后端·c#·asp.net·发送邮件·mailkit
冷冷的菜哥12 天前
ASP.NET Core文件分片上传
c#·asp.net·asp.net core·文件分片上传
前端世界14 天前
ASP.NET 实战:用 SqlCommand 打造一个安全的用户注册功能
后端·安全·asp.net
冷冷的菜哥15 天前
ASP.NET Core上传文件到minio
后端·asp.net·上传·asp.net core·minio
忧郁的蛋~16 天前
在.NET标准库中进行数据验证的方法
后端·c#·asp.net·.net·.netcore
jiasting23 天前
高通平台wifi--p2p issue
asp.net·p2p·issue