gpt4 book ai didi

Action Controller 模型中的 C# MVC 和 DateTime

转载 作者:太空狗 更新时间:2023-10-29 21:54:37 24 4
gpt4 key购买 nike

我有这个 Controller Action :

[HttpGet]
public ActionResult CreateForm(Models.ReminderModel model)
{
if (model.FkUserId == null && model.FkRoleId == null) {
model.FkUserId = UserSession.Current.UserId;
model.ReminderDate = DateTime.UtcNow;
}

return View(model);
}

如果未指定 URL 参数,操作会正常运行,但当我指定一些数据时,所有内容都会设置但是 ReminderDate。例如,请求是用

执行的
model[0][name]:FkUserId
model[0][value]:2
....
model[2][name]:ReminderDate
model[2][value]:2013-03-09T10:33:04.934Z
...

注意:参数是序列化的 jQuery View ,并且一直工作到现在。这是我们第一次尝试将 DateTime 传递回 Controller 操作。

在 Action Controller 中,model.FKUserId 将被正确设置,但是 ReminderDate 将被设置为 "0001-01-01T00:00:00.000Z ".

我错过了什么?

** 更新 **

事实证明,C# 不适用于 ISO 格式的日期时间字符串。它更喜欢UTC。 2013-03-05T16:23:00.000Z 之类的内容需要作为 u20130305212358000 (EST) 发送。绑定(bind)也足够了,但我认为这是最好的解决方案。

最佳答案

您会得到 1/1/0001 的日期,因为当 MVC 无法找到要提供的值,或者由于某种原因无法应用可用值时,日期的默认值仍然存在, DateTime1/1/0001DateTime.MinValue。如果您使用 DateTime?,您会看到 null。

最好使用 Fiddler 或 Firebug 检查请求并查看发送的值是什么。它很可能需要调整。您还可以通过 Form 集合检查当前表单的响应,并自己手动转换值。

一些替代方法是 MVC 模型绑定(bind)(尽管有些人提到了这种方法的缺点)。下面列出了更多信息:

关于 Action Controller 模型中的 C# MVC 和 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15228003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com