Search code examples
asp.net-mvcasp.net-mvc-4daterazor

MVC Razor - Default Value as Current date for textbox type date


I have a Textbox with type as date. I am trying to set default value of the textbox to current date.

@Html.TextBoxFor(x => x.Date, new { @id = "Date", @type = "date", 
                                    @value = DateTime.Now.ToShortDateString() })

The above line doesn't set default value. How to set default value as current date?


Solution

  • As Stephen Muecke said, you need to set the property's value on the model.

    // in controller method that returns the view.
    MyModel model = new MyModel();
    model.Date = DateTime.Today;
    
    return View(model);
    

    And your Razor would be:

    @Html.TextBoxFor(x => x.Date, "{0:yyyy-MM-dd}", new { @class = "form-control", @type = "date"})
    

    Note that the id and the name properties should be automatically assigned to the property name when using a For method, such as @Html.TextBoxFor(), so you don't need to explicitly set the id attribute.