Ajax Post 使用 Razor Pages

Ajax Post with Razor Pages

我正在使用 Asp.net Core Razor Pages 并希望在单击按钮时 POST 向服务器发送一些数据,但我无法在调用方法中获取客户端值,它始终为空:

<button type="button" class="btn btn-primary" onclick="save1()">Submit</button>

我的js代码:

function save1() {
          var order = { SerialNo: '1'};

            $.ajax({
                type: "POST",
                url: "@Url.Page("Index","Save1")",
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                data: JSON.stringify(order),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    alert('Success!');
                },
                failure: function (response) {
                    alert('error!');
                }
            });

        }

我的页面处理程序:

 public async Task<IActionResult> OnPostSave1Async(CreateOrderViewModel order)
    {
        //some code
    }

和我的视图模型:

public class CreateOrderViewModel
{

    public string SerialNo { get; set; }
    ...
}

你可能需要添加[FromBody]来接收发送的值,像这样:

型号:

       public class Test {
            public string SerialNo { get; set; }
            }

控制器:

 [HttpPost]
        public IActionResult Index([FromBody]Test order)
        {

            return View();
        }

        public IActionResult Index()
        {
            return View();
        }

查看:

<button type="button" class="btn btn-primary" onclick="save1()">Submit</button>
<script>
    function save1() {
        var order = { SerialNo: '1' };

            $.ajax({
                type: "POST",
                url: "test/Index",
                data: JSON.stringify(order),
                contentType: "application/json; charset=utf-8",
               dataType: "json",
                success: function () {
                alert('Success!');
                },
                failure: function (response) {
                alert('error!');
                }
                });

                }
</script>

结果: