首页 > 解决方案 > 使用 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");
        }

标签: c#ajaxstringasp.net-corenull

解决方案


您的控制器操作(我假设已配置为接受 POST 请求)

public string LoadChildrenAccounts(string parentID)

接受一个裸字符串作为参数,但您正在发布一个具有字符串 ( ) 类型属性的对象{ "parentID": "12345" }

尝试更改data: stringify({ "parentID": "12345" })data: JSON.stringify("12345")


推荐阅读