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

.NET 7.0 MVC中能否将date类型输入直接绑定到string类型属性?

在.NET 7.0 MVC中绑定date输入框到string属性的方法

可以直接将date类型输入框的值绑定到C#的string类型属性或控制器参数,但要注意一个关键细节:HTML的date输入框提交到后台的是ISO 8601标准格式的字符串(yyyy-MM-dd),而非用户在浏览器中看到的本地化显示格式(比如MM/dd/yyyy)。

直接绑定的实现示例

HTML代码

<input type="date" name="StringDate" />

C#模型属性

public class MyModel
{
    public string StringDate { get; set; }
}

控制器接收参数

[HttpPost]
public IActionResult MyAction(string StringDate)
{
    // 此时StringDate的值为ISO格式,比如用户选择2023年4月26日,值为"2023-04-26"
    // 后续业务逻辑
    return View();
}

获取本地化显示格式的字符串

如果需要得到用户看到的本地化格式(比如MM/dd/yyyy),可以在后台将ISO格式的字符串转换为DateTime,再按指定格式输出:

[HttpPost]
public IActionResult MyAction(string StringDate)
{
    if (DateTime.TryParse(StringDate, out DateTime selectedDate))
    {
        // 转换为MM/dd/yyyy格式的字符串
        string formattedDate = selectedDate.ToString("MM/dd/yyyy");
        // 使用formattedDate进行后续操作
    }
    return View();
}

关键说明

  • 浏览器对date输入框的显示格式由系统区域设置决定,但提交数据时严格遵循HTML标准,始终发送yyyy-MM-dd格式的字符串。
  • 直接绑定到string属性是MVC模型绑定的默认行为,无需额外配置,拿到的就是ISO格式的日期字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:33:12