MVC - 只需要修改视图中字段的时间值

发布于 2024-12-13 12:41:56 字数 75 浏览 5 评论 0原文

在视图中,我只需修改日期时间类型字段的时间部分。 我不确定这将如何运作。一种方法可能是传递提示,但不确定如何实现。

谢谢

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

遮了一弯 2024-12-20 12:41:56

您的问题不太清楚您想要做什么,但根据我收集的信息,我假设您只想显示日期并仅编辑时间。在这种情况下,可以像这样完成:

在您的模型中:

public class FooModel
{
    public string Date { get; set; }
    public string Time { get; set; }
}

在您的控制器中:

public class FooController
{
    [HttpGet]
    public ActionResult Foo()
    {
        var dateTime = DateTime.Now();
        var model = new Foo 
                        { 
                            Date = dateTime.ToShortDateString(), 
                            Time = dateTime.ToShortTimeString() 
                        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Foo(FooModel model)
    {
        DateTime updatedDateTime;
        var dateTime = string.Format("{0} {1}", model.Date, model.Time);
        var isValid = DateTime.TryParse(dateTime, out updatedDateTime);               

        if (!isValid)
        {
            ModelState.AddModelError("Time", "Please enter a valid Time.");
            return View(model);
        }

        // process updates

        return View("Success");
    }
}

在您的视图中:

@model FooModel

@using (Html.BeginForm()) {

    @Html.ValidationMessage("Time")

    Date: @Html.DisplayFor(m => m.Date) <br />
    Time: @Html.EditorFor(m => m.Time)


    <p>
        <input type="submit" value="Save" />
    </p>
}

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:

public class FooModel
{
    public string Date { get; set; }
    public string Time { get; set; }
}

In your controller:

public class FooController
{
    [HttpGet]
    public ActionResult Foo()
    {
        var dateTime = DateTime.Now();
        var model = new Foo 
                        { 
                            Date = dateTime.ToShortDateString(), 
                            Time = dateTime.ToShortTimeString() 
                        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Foo(FooModel model)
    {
        DateTime updatedDateTime;
        var dateTime = string.Format("{0} {1}", model.Date, model.Time);
        var isValid = DateTime.TryParse(dateTime, out updatedDateTime);               

        if (!isValid)
        {
            ModelState.AddModelError("Time", "Please enter a valid Time.");
            return View(model);
        }

        // process updates

        return View("Success");
    }
}

In your view:

@model FooModel

@using (Html.BeginForm()) {

    @Html.ValidationMessage("Time")

    Date: @Html.DisplayFor(m => m.Date) <br />
    Time: @Html.EditorFor(m => m.Time)


    <p>
        <input type="submit" value="Save" />
    </p>
}
岁月苍老的讽刺 2024-12-20 12:41:56

您可以使用ToString方法来更改格式。 此处列出了所有不同的格式选项。仅出于时间考虑,请跳至标题为“The "f" Custom Format Specifier”的部分

Console.WriteLine(TimeFld.ToString("hh:mm:ss.f", ci));
// Displays 07:27:15.0

在您的 MVC 视图中,您将执行以下操作

@TimeFld.ToString("hh:mm:ss.f", ci);

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"

Console.WriteLine(TimeFld.ToString("hh:mm:ss.f", ci));
// Displays 07:27:15.0

In your MVC View you would do

@TimeFld.ToString("hh:mm:ss.f", ci);
微凉 2024-12-20 12:41:56

请参阅DateTime.ToString()

另外,这里是标准格式选项列表

或者,您可以自行部署

在 Razor 中:

@Foo.ToString("MMMM dd, yyyy")

将返回(今天),

2011 年 11 月 8 日

See DateTime.ToString().

Also, here is a list of standard format options.

Or, you can roll your own.

In Razor:

@Foo.ToString("MMMM dd, yyyy")

would return (for today),

November 08, 2011

微暖i 2024-12-20 12:41:56

在 .NET 中,不可能仅更改 DateTime 字段的时间部分,因为 DateTime 是一个不可变的结构。这是来自 MSDN,“使用 DateTime 成员”

使用 DateTime 结构时,请注意 DateTime 类型是不可变值。因此,DateTime.AddDays 等方法会检索新的 DateTime 值,而不是增加现有值。以下示例说明如何使用语句 dt = dt.AddDays(1) 将 DateTime 类型增加一天。

public static void Main()
{
  Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

  DateTime dt = DateTime.Now;
  Console.WriteLine("Today is {0}", DateTime.Now.ToString("d"));

  // Increments dt by one day.
  dt = dt.AddDays(1);
  Console.WriteLine("Tomorrow is {0}", dt.ToString("d"));

}

如您所见,唯一有效的方法是为 DateTime 字段分配新值。 DateTime 类型确实支持时间操作方法 AddHoursAddMinutesAddSecondsAddMilliseconds。但是,这些方法仅返回新的DateTime,因此您必须将视图模型上的属性设置为新值才能使其显示在视图中。

您可能还想查看这篇文章:如何更改日期时间中的时间? . (乔恩·斯基特回答了)。

In .NET it is not possible to change only the time part of a DateTime field, because DateTime is an immutable struct. This is from MSDN, "Working with DateTime Members":

When working with the DateTime structure, be aware that a DateTime type is an immutable value. Therefore, methods such as DateTime.AddDays retrieve a new DateTime value instead of incrementing an existing value. The following example illustrates how to increment a DateTime type by a day using the statement dt = dt.AddDays(1).

public static void Main()
{
  Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

  DateTime dt = DateTime.Now;
  Console.WriteLine("Today is {0}", DateTime.Now.ToString("d"));

  // Increments dt by one day.
  dt = dt.AddDays(1);
  Console.WriteLine("Tomorrow is {0}", dt.ToString("d"));

}

As you can see, the only valid approach is to assign a new value to the DateTime field. The DateTime type does support the time-manipulation methods AddHours, AddMinutes, AddSeconds and AddMilliseconds. However, these methods only return a new DateTime 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文