您无权访问 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>
}