MVC - 只需要修改视图中字段的时间值
在视图中,我只需修改日期时间类型字段的时间部分。 我不确定这将如何运作。一种方法可能是传递提示,但不确定如何实现。
谢谢
In the view, I need to modify only the time part for a field which is of type datetime.
I am not sure how this would work. One way may be to pass a hint but not sure how this can be accomplished.
THanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的问题不太清楚您想要做什么,但根据我收集的信息,我假设您只想显示日期并仅编辑时间。在这种情况下,可以像这样完成:
在您的模型中:
在您的控制器中:
在您的视图中:
Your question isn't very clear on what you want to do but from what I gather I assume you want to display the date and edit only the time. In this case that can be accomplished like so:
In your model:
In your controller:
In your view:
您可以使用
ToString
方法来更改格式。 此处列出了所有不同的格式选项。仅出于时间考虑,请跳至标题为“The "f" Custom Format Specifier”的部分在您的 MVC 视图中,您将执行以下操作
You can use the
ToString
method to change the format. HERE is a listing of all the different format options. For time only, skip to the section titled "The "f" Custom Format Specifier"In your MVC View you would do
请参阅DateTime.ToString()。
另外,这里是标准格式选项列表。
或者,您可以自行部署。
在 Razor 中:
将返回(今天),
See DateTime.ToString().
Also, here is a list of standard format options.
Or, you can roll your own.
In Razor:
would return (for today),
在 .NET 中,不可能仅更改
DateTime
字段的时间部分,因为DateTime
是一个不可变的结构。这是来自 MSDN,“使用 DateTime 成员”:如您所见,唯一有效的方法是为
DateTime
字段分配新值。DateTime
类型确实支持时间操作方法AddHours
、AddMinutes
、AddSeconds
和AddMilliseconds
。但是,这些方法仅返回新的DateTime
值,因此您必须将视图模型上的属性设置为新值才能使其显示在视图中。您可能还想查看这篇文章:如何更改日期时间中的时间? . (乔恩·斯基特回答了)。
In .NET it is not possible to change only the time part of a
DateTime
field, becauseDateTime
is an immutable struct. This is from MSDN, "Working with DateTime Members":As you can see, the only valid approach is to assign a new value to the
DateTime
field. TheDateTime
type does support the time-manipulation methodsAddHours
,AddMinutes
,AddSeconds
andAddMilliseconds
. However, these methods only return a newDateTime
value, so you will have to set the property on your View Model to the new value for it to appear in your view.You may also want to check out this post: How to change time in datetime? . (Jon Skeet answered it).