You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

搜索后如何保留date输入框的用户选中值?

解决搜索后日期重置为当前的问题

问题核心是搜索后页面刷新,原有的初始化JS会重新执行,强制将日期设为当前,覆盖用户之前的选择。以下是两种可行的解决办法:

方法一:仅在输入框为空时设置默认日期

修改初始化脚本,只在输入框没有值的情况下才设置当前日期。这样如果用户已经选择过日期(或页面刷新后后端回填了值),就不会被覆盖。

修改后的脚本代码:

@section Scripts{
    <script>
    $(function(){
        const startInput = document.getElementsByName('start')[0];
        const endInput = document.getElementsByName('end')[0];
        
        // 仅当输入框无值时,设置为当前日期
        if (!startInput.value) {
            startInput.valueAsDate = new Date();
        }
        if (!endInput.value) {
            endInput.valueAsDate = new Date();
        }
    })
    </script>
}

方法二:从URL参数恢复用户选择的日期(适用于GET请求搜索)

如果搜索是通过GET方式提交,用户选择的日期会出现在URL的查询参数中。可以直接从URL提取这些参数,回填到输入框中。

修改后的脚本代码:

@section Scripts{
    <script>
    $(function(){
        const startInput = document.getElementsByName('start')[0];
        const endInput = document.getElementsByName('end')[0];
        
        // 解析URL中的查询参数
        const urlParams = new URLSearchParams(window.location.search);
        const savedStart = urlParams.get('start');
        const savedEnd = urlParams.get('end');
        
        // 优先使用保存的日期,无保存值时再设为当前日期
        if (savedStart) {
            startInput.value = savedStart;
        } else {
            startInput.valueAsDate = new Date();
        }
        
        if (savedEnd) {
            endInput.value = savedEnd;
        } else {
            endInput.valueAsDate = new Date();
        }
    })
    </script>
}

补充:POST请求场景的处理

如果搜索是POST提交,需要后端在返回页面时,将用户提交的start和end值回填到输入框的value属性中,比如:

<input type="date" name="start" value="@Model.StartDate" />
<input type="date" name="end" value="@Model.EndDate" />

再配合方法一的脚本,就能确保刷新后保留用户选择的日期。

内容的提问来源于stack exchange,提问作者Phatt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:30:50