c# - 使用 ajax 传递给 ASP.NET Core Controller 的参数始终为 null
问题描述
我正在将 mvc 应用程序升级到 .Net Core,并且难以通过 ajax 将字符串值传递给控制器。我尝试了在网上找到的各种解决方案([FormBody]
、前缀=
和其他一些),但没有运气。该值始终为空。我需要修复的核心发生了什么变化?
var result = "";
$.ajax({
url: "https://......./api/lookups/Search",
type: "POST",
data: JSON.stringify(g),
async: false,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
result = data;
},
done: function (data) {
result = data;
},
fail: function (data) {
result = data;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('request failed :' + errorThrown);
}
});
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace zpmAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class LookupsController : ControllerBase
{
private zBestContext db = new zBestContext();
// GET api/values
[HttpGet]
public string sayHello()
{
return "hello";
}
[HttpPost]
//[Route("api/Lookups/LocationSearch")]
public JsonResult LocationSearch(GeneralSearch g)
{
return new JsonResult( "hello from LocationSearch");
}
解决方案
您的控制器操作(我假设已配置为接受 POST 请求)
public string LoadChildrenAccounts(string parentID)
接受一个裸字符串作为参数,但您正在发布一个具有字符串 ( ) 类型属性的对象{ "parentID": "12345" }
。
尝试更改data: stringify({ "parentID": "12345" })
为data: JSON.stringify("12345")
推荐阅读
- python - 如何实施障碍以阻止玩家穿过墙壁
- r - R仅在列具有特定值时排列
- java - 如何仅用分钟格式化 LocalDateTime(截断秒)?
- caching - 如何使用 apollo 客户端处理在 graphql 的子查询中为嵌套对象返回不同值的查询
- python - Python:遍历列表给出语法错误
- python - 将字符串转换为numpy数组python
- python - 调用 getter 并写入 txt 文件
- c# - 通过 IP 地址连接时出现 OWIN 错误
- docker - 无法配置新的 dunglas/mercure 映像
- docker - 使用 GPUS 和 systemctl 运行 docker nvidia 容器