Current date and time - Default in MVC razor
Asked Answered
P

6

18

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.

  @Html.EditorFor(model => model.ReturnDate)
Pero answered 18/8, 2011 at 18:18 Comment(1)
You obviously must be done with this, but for other people coming here they should ask themselves Server time or Client time. There are answers below that could have very different results.Geary
P
24

Before you return your model from the controller, set your ReturnDate property to 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 ReturnDate returns the current date/time.

private DateTime _returnDate = DateTime.MinValue;
public DateTime ReturnDate{
   get{
     return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
   }
   set{_returnDate = value;}
}
Pianette answered 18/8, 2011 at 18:28 Comment(1)
That worked for me, except I was getting this error "system.datetime.now cannot be used like a method". Removing the brackets after DateTime.Now solved this for me.Dimphia
S
22

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
Satterwhite answered 16/8, 2017 at 9:27 Comment(0)
K
10

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

In the controller:

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

    return View(viewModel);
}
Kafir answered 18/8, 2011 at 18:32 Comment(1)
Looks like @Jamie answered at the same time as me. His works too! Same answer.Kafir
A
8

Isn't this what default constructors are for?

class MyModel
{

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

    public date ReturnDate {get; set;};

}
Autrey answered 24/8, 2011 at 13:54 Comment(0)
S
1

Date in a .razor file

<p>@DateTime.Today.toString()<p>

Sacristan answered 23/12, 2021 at 0:1 Comment(0)
H
1

If you want to only return the date without time. Use this.

<span>@DateTime.Today.ToString("d")<span>
Hamlin answered 15/7, 2022 at 8:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.