简体   繁体   English

动作控制器模型中的C#MVC和DateTime

[英]C# MVC and DateTime in action controller model

I have this 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);
}

The action behaves normally if no URL param is specified, but when I specify some data, everything gets set BUT ReminderDate . 如果未指定URL参数,则该动作的行为正常,但是当我指定一些数据时,一切都会设置BUT ReminderDate For example, the request is performed with 例如,使用

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

Note : the params are serialized view jQuery and always worked fine until now. 注意 :这些参数是序列化视图jQuery,到目前为止一直可以正常工作。 It's the first time we try to pass a DateTime back to a controller action. 这是我们第一次尝试将DateTime传递回控制器动作。

In the action controller, model.FKUserId will correctly be set, however ReminderDate will be set to "0001-01-01T00:00:00.000Z" . 在动作控制器中,将正确设置model.FKUserId ,但是ReminderDate将设置为"0001-01-01T00:00:00.000Z"

What am I missing? 我想念什么?

** Update ** ** 更新 **

As it turned out, C# will not work with ISO formatted date time strings. 事实证明,C#不适用于ISO格式的日期时间字符串。 It prefers UTC ones. 它更喜欢UTC。 Something like 2013-03-05T16:23:00.000Z needs to be sent as u20130305212358000 (EST). 2013-03-05T16:23:00.000Z需要以u20130305212358000 (EST)的形式发送。 A binding would've been sufficient as well, but I think this is the best solution. 绑定也足够了,但是我认为这是最好的解决方案。

You would get that date of 1/1/0001 because when MVC can't find a value to supply, or can't apply the available value for some reason, the date's default remains, which for DateTime is 1/1/0001 or DateTime.MinValue . 您将获得1/1/0001日期,因为当MVC找不到要提供的值,或者由于某种原因而无法应用可用值时,该日期的默认值将保持不变,对于DateTime ,该DateTime1/1/0001DateTime.MinValue If you used DateTime? 如果使用DateTime? , you would see null. ,您将看到null。

It would be good to use Fiddler or Firebug to inspect the request and see what the value being sent is. 使用Fiddler或Firebug检查请求并查看所发送的值将是很好的。 It most likely may need adjusted. 它很可能需要调整。 You could also check the current form's response via the Form collection and manually convert the value yourself too. 您还可以通过Form集合检查当前表单的响应,也可以自己手动转换值。

Some alternatives is MVC model binding (though some mention cons to this approach). 一些替代方法是MVC模型绑定(尽管有些提及不利于此方法)。 Some more info is listed below: 下面列出了一些更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM