Ajax提交数据至Controller后始终返回undefined问题排查
问题排查:提交数据至Action Controller后返回"undefined"
我将数据提交至Action Controller的model中,数据已成功传入model,但前端最终返回“undefined”,以下是我的代码,请帮忙排查问题:
前端代码
$(function () { $("#submit").click(function () { var jdata = { CompanyCode: 1, CompanyName: "test", }; $.ajax({ type: "POST", url: "/Services/getdata", data: JSON.stringify(jdata), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); }); });
C#后端代码
[HttpPost] public async Task<IActionResult> getdata([FromBody] model tmpModel) { return View(); }
问题原因
后端返回的是View(),这会输出视图的HTML内容,但前端dataType设置为json,前端会尝试把HTML解析成JSON对象,解析失败后要么进入error回调,要么在success中拿到的response不是预期的JSON结构,导致response.Name和response.DateTime取不到值,显示undefined。
解决方案
如果需要返回JSON数据给前端,后端应使用Json()方法返回结构化的JSON对象:
[HttpPost] public async Task<IActionResult> getdata([FromBody] model tmpModel) { // 根据业务需求构造返回数据,示例中使用传入的CompanyName和当前时间 var responseData = new { Name = tmpModel.CompanyName, DateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }; return Json(responseData); }
同时确保:
- 后端的
model类已正确定义CompanyCode和CompanyName属性,确保能正常接收前端数据 - 前端请求的
url路径正确,指向对应的Controller和Action
内容的提问来源于stack exchange,提问作者user2015306
相关产品推荐
相关产品推荐

