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

ASP.NET Core MVC提交筛选后日期输入框无法填充模型值的问题

ASP.NET Core MVC日期输入框无法填充值的解决方法

问题根源

  1. 格式不匹配:HTML5的input[type="date"]要求value属性必须是yyyy-MM-dd格式的字符串,直接输出DateTime对象会使用系统默认格式,大概率不符合要求。
  2. 无效值赋值:控制器中使用GetValueOrDefault()会把null的日期参数转为DateTime.MinValue(0001-01-01),这个日期超出浏览器日期输入框的有效范围,不会被显示。
  3. 手动绑定易出错:手动设置value属性没有处理null情况,也没做格式转换,导致绑定失败。

解决方案

步骤1:修正控制器的模型赋值

去掉GetValueOrDefault(),直接保留原始的可空值,避免生成无效日期:

public async Task<IActionResult> Index(...,
           string filterString,
           DateTime? startDate = null,
           DateTime? endDate = null,)
{
    // ...
    var model = new ViewModel(...)
                    {
                        StartDate = startDate, // 直接赋值,保留null
                        EndDate = endDate,
                        FilterString = filterString,
                    };

    return View(model);
}

步骤2:优化视图的日期输入框

推荐使用ASP.NET Core的标签助手asp-for,它会自动处理模型绑定、日期格式转换和null值处理,比手动写value更可靠:

<span>Date after: </span>
<input type="date" asp-for="StartDate" asp-route-filterString="@Model.FilterString" class="form-control" />

<span>Date before: </span>
<input type="date" asp-for="EndDate" asp-route-filterString="@Model.FilterString" class="form-control" />

如果必须手动设置value,则需要显式格式化日期并处理null:

<span>Date after: </span>
<input type="date" name="startDate" id="startDate" asp-route-filterString="@Model.FilterString" class="form-control" 
       value="@(Model.StartDate.HasValue ? Model.StartDate.Value.ToString("yyyy-MM-dd") : string.Empty)" />

<span>Date before: </span>
<input type="date" name="endDate" id="endDate" asp-route-filterString="@Model.FilterString" class="form-control" 
       value="@(Model.EndDate.HasValue ? Model.EndDate.Value.ToString("yyyy-MM-dd") : string.Empty)" />

原理说明

  • asp-for标签助手会自动读取模型的StartDate/EndDate值,将可空DateTime转换为符合要求的yyyy-MM-dd格式字符串;如果值为null,则输出空字符串,浏览器会显示空白输入框。
  • 保留模型的可空性,避免生成浏览器无法识别的无效日期,确保筛选后的值能正确回显到输入框中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:39:24