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;
}
相关推荐
元直数字电路验证3 天前
ASP.NET Core Web APP(MVC)开发中无法全局配置 NuGet 包,该怎么解?
前端·javascript·ui·docker·asp.net·.net
William_cl3 天前
拆解ASP.NET MVC 视图模型:为 View 量身定制的 “数据小票“
后端·asp.net·mvc
宝桥南山3 天前
.NET10 - 尝试一下Blazor Web Assembly Standalone App的fingerprint新特性
microsoft·微软·c#·asp.net·.net·.netcore
William_cl4 天前
从 MVC 5 到 Core MVC:ASP.NET MVC 框架的 “进化之路“
后端·asp.net·mvc
忧郁的蛋~5 天前
ASP.NET Core中创建中间件的几种方式
后端·中间件·asp.net
元直数字电路验证5 天前
在ASP.NET Core Web APP(MVC)开发中,如何处理Docker容器的持久化数据?
后端·docker·asp.net
sheji34167 天前
【开题答辩全过程】以 基于Asp.Net网上图书店的设计与实现为例,包含答辩的问题和答案
后端·asp.net
sky-stars7 天前
Visual Studio 2022 安装使用:Entity Framework Core
asp.net·.netcore·visual studio
合作小小程序员小小店7 天前
web开发,在线%蛋糕销售%管理系统,基于asp.net,webform,c#,sql server
开发语言·后端·asp.net·html5·教育电商
宝桥南山8 天前
.NET - .NET Aspire的Command-Line和GitHub Copilot
microsoft·微软·c#·asp.net·.net·.netcore