問題簡介:AJAX post data is null in controller mvc or WebApi
問題場景:我在做.net mvc項目時需要用到Ajax往后端的WebApi Service請求數據時,發現通過url往后端進行get請求沒有任何問題,但是當我使用Post請求時,無論是將數據集包在對象中還是將數據以單個值一個一個往后台進行Post請求,后台的DataModel總是無法獲取到Post請求中Body里面的數據。
下面就是我當時的代碼:
后端WebApi接口:
[Route("SchoolService/AddOne")] [HttpPost] public Result<string> AddOne(SchoolModel data) { SchoolModel AddValue = new SchoolModel() { Id = data.Id, Name = data.Name, Address = data.Address }; SchoolDTO.GetInstance().AddEntity(data); return new Result<string>("success"); }
前端頁面:Index.cshtml
注:這里的組件我用的是Element-UI樣式
<el-form ref="School" :model="School" label-width="80px"> <el-form-item label="ID" prop="Id"> <el-input v-model="School.Id" placeholder="請輸入內容"></el-input> </el-form-item> <el-form-item label="學校名"> <el-input v-model="School.Address" placeholder="請輸入內容"></el-input> </el-form-item> <el-form-item label="地址"> <el-input v-model="School.Name" placeholder="請輸入內容"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @@click="AddOne()">立即添加</el-button> <el-button @@click="resetForm()">重置</el-button> </el-form-item> </el-form>
前端Ajax請求:
注:前端頁面是MVC控制器的視圖頁面,但是引入了Vue.js。下面代碼中有部分Vue代碼。
var app = new Vue({ el: '#main-content', data: { School: { }, }, methods: { //添加一條學校信息 AddOne: function () { const that = this; var data = that.School; console.log("that.School", data); //$.post("/SchoolService/AddOne", that.School) 這個試了也不行 $.ajax({ url: '/SchoolService/AddOne', async: false, dataType:'JSON' type: "POST", data: data,//這里無論使用哪種形式例如{"data":data},或者直接 //{"Id":1,"Name":2,"Address":3}都不行 error: function (res) { console.log(res); }, success: function (res) { console.log(res.data); } }) }, }, }
但是令人感到詭異的一點 就是上面的WebApi接口我使用PostMain來進行測試是沒有任何問題的!
PostMain請求案例:
這就證明了我后端接口肯定是沒問題的,問題肯定出在前端Ajax請求上面!
后來我查了很多國內網站試了很多方法都沒有效果,實在無奈去國外翻英文帖子終於找到一個遇到和我類似問題的哥們,下面也有解決方案,試了下果然可以!
成功Ajax請求案例:
AddOne: function () { const that = this; var data = that.School; console.log("that.School", data); $.ajax({ url: '/SchoolService/AddOne', dataType: "json", type: "POST", contentType: 'application/json', data: JSON.stringify(data),//關鍵點 async: true, processData: false, cache: false, success: function (data) { that.$message({ type: 'success', message: '添加成功!' }); that.GetSchoolData(); }, error: function (xhr) { that.$message({ type: 'info', message: '錯誤!' }); } }); },