简体   繁体   English

使用Ajax传递给ASP.NET Core Controller的参数始终为null

[英]Parameter passed to ASP.NET Core Controller using ajax is always null

I am upgrading mvc application to .Net Core and am having difficulty passing a string value via ajax to the controller. 我正在将mvc应用程序升级到.Net Core,并且难以通过ajax将字符串值传递给控制器​​。 I have tried various solutions I found on the web ( [FormBody] , prefixing with = , and some others), but no luck. 我尝试了各种在Web上找到的解决方案( [FormBody] ,以= [FormBody] ,以及其他一些解决方案),但是没有运气。 The value is always null. 该值始终为空。 What has changed in Core that I need to fix? 我需要修复的Core发生了什么变化?

      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");
        }

Your controller action (that I am assuming is configured to accept POST requests) 您的控制器操作(我假设已配置为接受POST请求)

public string LoadChildrenAccounts(string parentID)

accepts a bare string as parameter but you are POSTing an object with a property of type string ( { "parentID": "12345" } ). 接受一个裸字符串作为参数,但是您要发布一个属性为string类型的对象( { "parentID": "12345" } )。

Try changing data: stringify({ "parentID": "12345" }) to data: JSON.stringify("12345") 尝试将data: stringify({ "parentID": "12345" })更改为data: JSON.stringify("12345")

It appears I have been dealing with a Cors issue now have it working using the modified coded below in the Startup.cs and Controller. 看来我一直在处理Cors问题,现在可以使用下面在Startup.cs和Controller中修改的代码来使其工作。

The drawback to this is that "Content-Type: 'application/json'" must be added to the header on the client side in order it to work. 这样做的缺点是必须将“ Content-Type:'application / json'”添加到客户端的标头中才能起作用。 I would prefer not to do this because it would require the customers to make the update to their code. 我不希望这样做,因为这将要求客户对其代码进行更新。 Everything I have read says the shown modifications to the Startup.cs file should allow me to process with out modifying the post header, but the Application seams to be ignoring it. 我读过的所有内容都表明,对Startup.cs文件的所示修改应允许我进行处理而无需修改post标头,但是Application似乎忽略了它。

using System.Collections.Generic;
using dbzBest.Models;
using Microsoft.AspNetCore.Mvc;

namespace zpmAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Consumes("application/json")]
    public class PropertyController : ControllerBase
    {
        [HttpPost]
        public List<PropertyTile> Search(PropertySearch s)
        {
            try
            {
                List<PropertyTile> tiles = new List<PropertyTile>();
                dbzBest.Data.Properties db = new dbzBest.Data.Properties();
                tiles = db.Search(s);
                return tiles;
            }
            catch (System.Exception ex)
            {
                PropertyTile e = new PropertyTile();
                e.Description = ex.Message;
                List<PropertyTile> error = new List<PropertyTile>();
                error.Add(e);
                return error;
            }
        }
    }
}

In the Startup.cs file 在Startup.cs文件中

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {

                app.UseHsts();
            }

            /*add this line for CORS*/
            app.UseCors(opt => opt.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在 ASP.NET Core 中使用 Ajax 将参数传递给控制器​​始终为 NULL? - Why passed param with Ajax to controller in ASP.NET Core is always NULL? 在 ASP.Net Core 5 MVC 控制器中,当传递包含小数的 JSON 对象 FromBody 时,模型始终为空 - In ASP.Net Core 5 MVC Controller, when passed a JSON object FromBody that contains a decimal the model is always null ASP.Net Core 3.1:控制器方法总是从 HttpPost 调用接收 NULL 参数 - ASP.Net Core 3.1: Controller method always recieves NULL parameter from HttpPost call ASP.NET Core MVC controller 接收 null 来自 Z2705A83A5A0659CCE34583972 调用的输入参数 - ASP.NET Core MVC controller receives null for input parameter from ajax call jQuery数据表-ASP.NET控制器参数始终为null - jQuery datatable - ASP.NET controller parameter always null ASP.NET Core API POST 参数始终为空 - ASP.NET Core API POST parameter is always null 一些值为空 AJAX 调用控制器 ASP.Net Core - Some value are null AJAX call to controller ASP.Net Core ASP.NET Core Web Application using .NET 5.0: IFormFile always null when passing from view to controller - ASP.NET Core Web Application using .NET 5.0: IFormFile always null when passing from view to controller ASP.NET Core MVC 使用 ajax 将模型发布到控制器 - ASP.NET Core MVC posting a model to controller using ajax ASP.NET CORE,查看 model 的所有字段为 null 时传递回 Z9BBF373797BF7CF7BA62C80023 - ASP.NET CORE, View model has all fields as null when passed back to Controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM