简体   繁体   English

AJAX 发布数据到达 ASP.NET Core 2.1.1 控制器时为空

[英]AJAX post data is null when it reaches the ASP.NET Core 2.1.1 controller

I have a problem posting a value from java-script in my razor page to a controller.我在将剃刀页面中的 java-script 中的值发布到控制器时遇到问题。 - the value received is always null. - 收到的值始终为空。

I have seen similar questions being asked, but have not been able to find the right solution to the problem.我看到有人问过类似的问题,但一直无法找到问题的正确解决方案。

I get to a break point in the controller, (so the routing is okay) but the parameter value passed is always null, and not being the sharpest in java-script, I would like some tips from you folks.我在控制器中遇到了一个断点(所以路由是可以的)但是传递的参数值始终为空,并且不是 java-script 中最清晰的,我想从你们那里得到一些提示。

I basically have the java-script below:我基本上有下面的java脚本:

 var clickButton = function (buttonId) {
        $.ajax({
            type: "POST",
            async: false,
            cache: false,
            crossDomain: false,
            contentType: "application/json; charset=utf-8",
            url: "v1/buttons",
            dataType: "json",
            data: '{ buttonId:'+JSON.stringify( "buttonId" ) + '}',
            success: function (result) {
                //console.log("clickButton OK => " + result);
            }, //success: function (result) {
            timeout: 500 // 0.5 sec.
        }); //$.ajax({
    }//var clickButton = function(buttonNo) {

and the C# controller code below too:以及下面的 C# 控制器代码:

[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
 ...
  [HttpPost]
  public IActionResult OnButtonClicked( string buttonId )
  {
    // buttonId = null !!!
   ...

I have a similar problem getting a boolean value across to another controller.我有一个类似的问题,将布尔值传递到另一个控制器。 where the bool is always false.. ie the default value.其中 bool 始终为 false .. 即默认值。 I am wondering if it is a security issue, with not allowing the post to contain data, when the user is unauthorized...我想知道这是否是一个安全问题,当用户未经授权时不允许帖子包含数据......

The problem was in the JSON, and I got the value through with this minor change, but it was hiding well.问题出在 JSON 中,我通过这个小改动获得了价值,但它隐藏得很好。

 var clickButton = function (buttonNo) {
     console.log("clicked: " + buttonNo);
     $.ajax({
         type: "POST",
         url: "v1/buttons/",
         dataType: "json",
         data: { "buttonId": buttonNo }, // < === this is where the problem was !!
         success: function (result) {
         }, //success: function (result) {
      }); //$.ajax({
    }//var clickButton = function(buttonNo) {

I've changed the controller to receive a string to id the button.我已经改变了控制器来接收一个字符串来标识按钮。 And it now looks like this:现在看起来像这样:

[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
  ...
  [HttpPost]
  public IActionResult PostButtonClick( string buttonId ) {
    // buttonId now has a value !!!
  }
} 

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

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