如何将 DateTime 值传递给 AJAX,然后传递给控制器操作?

问题描述 投票:0回答:1
c# ajax asp.net-core razor
1个回答
0
投票

您无权访问 JavaScript 中的 Razor 变量。您可以使用以下代码:

public IActionResult GetData(DateTime fromDate, DateTime toDate)
  {
      return ViewComponent(nameof(GetCustomerData), new { fromDate, toDate });
  }

@{
    var fromDate = DateTime.Today;
    var toDate = DateTime.Today.AddDays(1);
}
@Html.Hidden("fromDate", fromDate)
@Html.Hidden("toDate", toDate)

<button type="button" onclick="getData()">Get data</button>



@section scripts
    {

    <script>
        function getData() {


            var fromDate = $('#fromDate').val();
            var toDate = $('#toDate').val();
            $.ajax({
                url: '@Url.Action("GetData", "Home")',
                data: { fromDate: fromDate, toDate: toDate },
                success: function (data) {
                    $("#dataId").html(data);
                },
                error: function (xhr, status, error) {
                    console.log(xhr.responseText);
                }
            })
        }
    </script>
}
© www.soinside.com 2019 - 2024. All rights reserved.