Current date and time - Default in MVC razor

后端 未结 4 637
梦如初夏
梦如初夏 2020-12-14 20:30

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(mo         


        
相关标签:
4条回答
  • 2020-12-14 21:04

    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);
    }
    
    0 讨论(0)
  • 2020-12-14 21:13

    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
    
    0 讨论(0)
  • 2020-12-14 21:13

    Isn't this what default constructors are for?

    class MyModel
    {
    
        public MyModel()
        {
            this.ReturnDate = DateTime.Now;
        }
    
        public date ReturnDate {get; set;};
    
    }
    
    0 讨论(0)
  • 2020-12-14 21:16

    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;}
    }
    
    0 讨论(0)
提交回复
热议问题