asp.net-mvc 当前日期和时间 - MVC 剃刀中的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7112127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:25:19  来源:igfitidea点击:

Current date and time - Default in MVC razor

asp.net-mvcasp.net-mvc-3asp.net-mvc-2razorhtml-helper

提问by ZVenue

When the MVC view page with this textbox, loads , I would like to display current date and time by default. How can I do this? in razor.

当带有此文本框的 MVC 视图页面加载时,我想默认显示当前日期和时间。我怎样才能做到这一点?在剃须刀。

  @Html.EditorFor(model => model.ReturnDate)

回答by Jamie Dixon

Before you return your model from the controller, set your ReturnDateproperty to DateTime.Now()

在从控制器返回模型之前,将ReturnDate属性设置为DateTime.Now()

myModel.ReturnDate = DateTime.Now()

return View(myModel)

Your view is not the right place to set values on properties so the controller is the better place for this.

您的视图不是在属性上设置值的正确位置,因此控制器是更好的位置。

You could even have it so that the getter on ReturnDatereturns the current date/time.

您甚至可以拥有它,以便 getter onReturnDate返回当前日期/时间。

private DateTime _returnDate = DateTime.MinValue;
public DateTime ReturnDate{
   get{
     return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
   }
   set{_returnDate = value;}
}

回答by Tink

If you want to display date time on view without model, just write this:

如果你想在没有模型的情况下在视图上显示日期时间,只需写下:

Date : @DateTime.Now

The output will be:

输出将是:

Date : 16-Aug-17 2:32:10 PM

回答by Lee DeLapp

You could initialize ReturnDate on the model before sending it to the view.

您可以在将模型发送到视图之前在模型上初始化 ReturnDate。

In the controller:

在控制器中:

[HttpGet]
public ActionResult SomeAction()
{
    var viewModel = new MyActionViewModel
    {
        ReturnDate = System.DateTime.Now
    };

    return View(viewModel);
}

回答by Jeremy Bell

Isn't this what default constructors are for?

这不是默认构造函数的用途吗?

class MyModel
{

    public MyModel()
    {
        this.ReturnDate = DateTime.Now;
    }

    public date ReturnDate {get; set;};

}