简体   繁体   English

Razor Pages.NetCore OnPost 处理程序

[英]Razor Pages .NetCore OnPost Handler

I am working on a project in C# with.NetCore Razor Pages and I have this page where a user makes an appointment by completing some fields.我正在使用.NetCore Razor 页面在 C# 中开展一个项目,我有这个页面,用户通过完成一些字段进行预约。

I have this field that is a calendar and the user can select a date from it.我有这个字段是一个日历,用户可以 select 从中获取日期。 Based on that date I want to populate a drop down with a list of hours that are available for an appointment.根据该日期,我想用可用于约会的时间列表填充下拉列表。

I tried to use Handlers like OnPost() but that requires a submit button, but I only have the calendar input.我尝试使用像 OnPost() 这样的处理程序,但这需要一个提交按钮,但我只有日历输入。

This is the code I use in my Razor Page for the calendar这是我在日历的 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>

In my model page I should have something like在我的 model 页面中,我应该有类似的东西

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

Is there any other function that I can use so when the user chooses a date from the calendar the dropdown will be populated with the available hours?是否有任何其他 function 我可以使用,因此当用户从日历中选择日期时,下拉菜单将填充可用时间?

EDIT In my Razor Page在我的 Razor 页面中编辑

@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>

In my model Page在我的 model 页面中

[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);

}

The problem is that after I send the json model to the dropdown and the values appear in the dropdown I can't take the option that is selected (in debug after choosing an option the Time property appears null)问题是,在我将 json model 发送到下拉列表并且值出现在下拉列表中之后,我无法选择所选的选项(在选择选项后的调试中,时间属性显示为空)

You can write an onchange function and then use ajax to send data to backend.Below is a simple demo.你可以写一个onchange function 然后使用 ajax 将数据发送到后端。下面是一个简单的演示。

 <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>
}

Backend:后端:

  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);
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 属性值在 Razor 页面中重置 OnPost - Property values reset OnPost in Razor Pages Razor 页面:值不会从 OnGet() 停留在 OnPost() - Razor Pages: Values not staying from OnGet() to OnPost() 如何将 IPageFilter 仅应用于 razor 页面中的 OnPost 处理程序 - How to apply IPageFilter to only OnPost handler in razor page 当 onPost() 触发时,Razor 页面公共字段变为 NULL - Razor Pages public field becomes NULL when onPost() triggered Razor Pages OnPost方法中的Page()方法有什么作用? - What does Page() method in Razor Pages OnPost method do? 如何在 .netcore 6 razor 页面中使用 FormHelper 和 FluentValidation - How to use FormHelper and FluentValidation in .netcore 6 razor pages Razor Pages OnPost - 父页面是否可以使用在创建时传递给它的部分的相同部分模型? - Razor Pages OnPost - Can the parent page use the same partial model that is passed to its partial on creation? ASP.NET Core 2.2 Razor Pages 为什么 OnPost() 有效,而 OnPostAsync() 无效? - ASP.NET Core 2.2 Razor Pages why does OnPost() work, but OnPostAsync() doesn't? Razor 页面 ASP.NET 核心 - OnPost() 使用 datatables.net 搜索栏不返回任何对象 - Razor Pages ASP.NET Core - OnPost() using datatables.net search bar returns no objects 带有 Razor 页面的区域中的 OnPost 不起作用 - OnPost in Area with Razor page not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM