通过 ajax 发送数据在 Post 方法中给出空值

Sending data via ajax gives null value in Post method

我正在尝试使用 ajax 通过 Ajax

在我的 .net Core Razor 页面模型上发送数据

这是我的 Razor 页面代码:

    $(function () {
        $('#placeRequest').on('click', function () {
            
            $.ajax({
                type: "POST",
                url: "/Index?handler=PlaceRequest",
                data: $('#select').val(),
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function () {
                    alert('Posted using jQuery')
                }
            });
        });
    });


<form method="post">
    <select id="select" class="form-control"></select>

      <div class="form-group button-position col-md4">
          <input type="submit" id="placeRequest" name="placeRequest" value="Place Request" asp-page-handler="PlaceRequest" class="btn btn-primary" />
      </div>
</form>

在我的页面模型中

public IActionResult OnPostPlaceRequest(string myData)
{
   //here myData is null
}

问题是我的 Post 函数中的 myData 为空。我在 ajax 脚本函数中遗漏了什么吗?

data:{myData:$('#select').val()},

我发现你最后 case.I 认为问题是你的下拉列表没有值。$('#select').val() 是获取下拉列表的 value

你最后一个例子,Asp-for绑定了下拉列表的值,你的select值为null,所以时间为null。您应该按如下方式更改代码。

$("#select").append("<option value='" + item.hour + "'>"  + "'>" + item.hour + "</option>");

然后是代码:

 <select id="select" asp-for="Time" class="form-control"></select>

将成功绑定Time

如果你想ajax提交值,你只需要像@Shaybakov那样更改代码。