![](/img/trans.png)
[英]Why passed param with Ajax to controller in ASP.NET Core is always NULL?
[英]Parameter passed to ASP.NET Core Controller using ajax is always null
我正在將mvc應用程序升級到.Net Core,並且難以通過ajax將字符串值傳遞給控制器。 我嘗試了各種在Web上找到的解決方案( [FormBody]
,以=
[FormBody]
,以及其他一些解決方案),但是沒有運氣。 該值始終為空。 我需要修復的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");
}
您的控制器操作(我假設已配置為接受POST請求)
public string LoadChildrenAccounts(string parentID)
接受一個裸字符串作為參數,但是您要發布一個屬性為string類型的對象( { "parentID": "12345" }
)。
嘗試將data: stringify({ "parentID": "12345" })
更改為data: JSON.stringify("12345")
看來我一直在處理Cors問題,現在可以使用下面在Startup.cs和Controller中修改的代碼來使其工作。
這樣做的缺點是必須將“ Content-Type:'application / json'”添加到客戶端的標頭中才能起作用。 我不希望這樣做,因為這將要求客戶對其代碼進行更新。 我讀過的所有內容都表明,對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;
}
}
}
}
在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.