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

Razor Pages日期值无法传递至其他页面的问题求助

问题根源

你传递日期时使用了ToShortDateString(),生成的短日期字符串格式大概率与ASP.NET Razor Pages默认的模型绑定日期解析规则不匹配,导致框架无法将URL中的日期字符串正确转换为DateTime类型,最终只能使用DateTime的默认值(01/01/0001)。

虽然URL里显示的日期看起来正常,但服务器端的模型绑定器无法识别该格式,所以解析失败。

解决方案

方案1:直接传递DateTime对象(推荐)

在RoomSearch页面的"Book Now"链接中,不要手动格式化日期,直接传递DateTime类型的StartDate和EndDate即可,Razor框架会自动将其转换为模型绑定器能正确解析的标准格式(通常是ISO 8601格式):

修改RoomSearch页面中的链接代码:

<td>
    <a asp-page="/BookRoom" 
       asp-route-roomtypeid="@room.Id" 
       asp-route-startdate="@Model.StartDate" 
       asp-route-enddate="@Model.EndDate">
        Book Now
    </a>
</td>

方案2:显式指定日期格式并配置模型绑定

如果必须使用自定义短日期格式,需要在BookRoom页面的DateTime属性上添加[DisplayFormat]属性,明确告知模型绑定器如何解析传入的日期字符串:

修改BookRoomModel的属性:

[BindProperty(SupportsGet = true)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }

[BindProperty(SupportsGet = true)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }

同时要确保RoomSearch页面中传递的日期格式和这里指定的一致,比如改为@Model.StartDate.ToString("MM/dd/yyyy")。

验证方法

修改完成后,点击"Book Now"链接,查看Visual Studio调试器里BookRoomModel的StartDate和EndDate值,应该能正确获取用户选择的日期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:17:47