简体   繁体   中英

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. I have tried various solutions I found on the web ( [FormBody] , prefixing with = , and some others), but no luck. The value is always null. What has changed in Core that I need to fix?

      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)

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

Try changing data: stringify({ "parentID": "12345" }) to 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.

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. 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.

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

    // 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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM