我有一个索引页面和指向搜索页面的链接。我希望在运行页面搜索时将今天的默认日期显示为“16/11/2023”,但是当选择“15/11/2023”等另一个日期并按“搜索”按钮时,将显示结果并加载返回到页面时,选择的日期将为“15/11/2023”,而不是默认日期“16/11/2023”。
文件Search.cshtml中的代码
<table>
<tr>
<td><label>Date</label></td>
<td><input type="date" id="date" name="date" value="" /></td>
<td><button type="submit" id="btnSearch" asp-page-handler="Data">Search</button></td>
</tr>
</table>
<script type="text/javascript">
var initialLoad = true;
if (initialLoad) {
// Do work that is done when the page was first loaded.
document.getElementById('date').value = new Date().toISOString().substring(0, 10);
} else {
// Do work when it's not the initial load.
}
</script>
Search.cshtml.cs 中的代码
public void OnPostData()
{
string str_date = Request.Form["date"];
// Code show result search
}
感谢大家的帮助。
我希望在运行页面搜索时将今天的默认日期显示为 “16/11/2023”,但是当选择另一个日期如“15/11/2023”时 按“搜索”按钮,将显示并加载结果 返回页面,选择的日期将是“15/11/2023”,而不是 默认日期“16/11/2023”
您可以使用 ViewData 在 Razor 页面中显示日期,并将其值设置为当前日期或默认选择的日期,由于页面已经获取了日期并将其显示在页面上,因此您不需要在 OnGet 方法中设置默认日期。然后就可以使用[BindProperty]自动将表单字段绑定到Date属性,然后使用ViewData将selecteddate设置为Date属性的值,可以使用以下代码作为参考:
控制器:
[BindProperty]
public string Date { get; set; }
public IActionResult OnPost()
{
ViewData["SelectedDate"] = this.Date;
return Page();
}
页码:
<form method="post">
<table>
<tr>
<td><label>Date</label></td>
<td><input type="date" id="date" name="date" value="@((string)ViewData["SelectedDate"] ?? DateTime.Now.ToString("yyyy-MM-dd"))" /></td>
<td><button type="submit">search</button></td>
</tr>
</table>
</form>
默认日期:
选择日期并搜索后: