首页 > 解决方案 > Razor Pages .NetCore OnPost 处理程序

问题描述

我正在使用 .NetCore Razor Pages 使用 C# 开发一个项目,并且我有这个页面,用户通过完成某些字段来进行预约。

我有这个字段是一个日历,用户可以从中选择一个日期。根据该日期,我想用可用于约会的时间列表填充下拉列表。

我尝试使用像 OnPost() 这样的处理程序,但这需要一个提交按钮,但我只有日历输入。

这是我在 Razor 页面中用于日历的代码


<div class="form-group col-md-4">
    <label asp-for="StartDate"></label>
    <input asp-for="StartDate" class="form-control" />
    <span class="text-danger" asp-validation-for="StartDate"></span>
</div>

在我的模型页面中,我应该有类似的东西

 public IActionResult OnPostStartDate()
 {
    \\code that brings from the database the available hours 
 }

我可以使用任何其他功能,因此当用户从日历中选择日期时,下拉菜单将填充可用时间?

在我的剃刀页面中编辑

@section Scripts {
    <script>
          $("#StartDate").on("change", function () {
              var time = $(this).val();
              $("#select").empty();
              $("#select").append("<option value=''>select </option>");
              $.getJSON(`?handler=Time&time=${time}`, (data) => {
                $.each(data, function (i, item) {
                $("#select").append("<option value='"  + "'>" + item.hour + "</option>");
                });
            });      
        });
    </script>
}





<form class="form-style" method="post" id="createBTForm">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="StartDate" class="control-label"></label>
            <input asp-for="StartDate" class="form-control" />
            <span asp-validation-for="StartDate" class="text-danger"></span>
        </div>

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

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

在我的模型页面中

[Required(ErrorMessage = "Field cannot be empty!")]
[BindProperty]
[DataType(DataType.Date)]
[Display(Name = "Start Date:")]
public DateTime StartDate { get; set; }

//this is null after selecting an option from the dropdown
[BindProperty]
public string Time { get;set; }

//this is the method that should work when I press the Place Request submit button
public async Task<IActionResult> OnPost()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    //here I send the data to the database     
           
    return Redirect(Url.Page(indexPage));
}


//this is the method that puts the values on the dropdown (this works)
public async Task<IActionResult> OnGetTime(DateTime time)
{
    //Here I set my model based on database data
      var finalHours = leaveFromLocations.Where(f => !unavailable.Contains(f));

      foreach (var h in finalHours)
      {
             model.Add(new Hours
             {
                  Hour = h
              });
      }

      return new JsonResult(model);

}

问题是,在我将 json 模型发送到下拉列表并且值出现在下拉列表中之后,我无法选择所选择的选项(在选择选项后的调试中,Time 属性显示为空)

标签: c#asp.net-corehandler

解决方案


你可以编写一个onchange函数,然后使用ajax向后端发送数据。下面是一个简单的demo。

 <form method="post">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Time.StartDate" class="control-label"></label>
            <input asp-for="Time.StartDate" class="form-control" />
            <span asp-validation-for="Time.StartDate" class="text-danger"></span>
        </div>
        <select id="select" asp-for="Time.Hour" class="form-control"></select>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
</form>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
    $("#Time_StartDate").on("change", function () {
        var time = $(this).val();
        $("#select").empty();
        $("#select").append("<option value=''>select </option>");
        $.getJSON(`?handler=Time&time=${time}`, (data) => {
            $.each(data, function (i, item) {
                //"id" and "hours" is in your JsonResult(model),and remember The first letter of the attribute must be lowercase
                $("#select").append("<option value='" + item.id + "'>" + item.hours + "</option>");
            });
        });
    });
</script>
}

后端:

  public IActionResult OnGetTime(DateTime time)
    {
        //this is a fake data,you can query your data here.
        var model = new List<Hour>
        {
            new Hour
            {
                Id=1,
                Hours=1
            },
            new Hour
            {
                Id=2,
                Hours=2
            },
        };
        return new JsonResult(model);
    }

测试结果: 在此处输入图像描述


推荐阅读