MVC Razor - default value as current date for text field type date

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

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

The line above does not have a default value. How to set default value as current date?

+7
date asp.net-mvc razor asp.net-mvc-4
source share
4 answers

As Stephen Mukke said, you need to set the property 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 will:

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

Note that the id and name properties should be automatically assigned the name of the property when using the For method, for example @Html.TextBoxFor() , so you do not need to explicitly set the id attribute.

+20
source share

This is the best way to manage your presentation.

 @Html.TextBoxFor(x=> x.Date, new { @Value = @DateTime.Now.ToShortDateString() }) 
+19
source share

Another solution:

  @Html.TextBoxFor(model=>model.CreatedOn, new{@value= System.DateTime.Now}) 

It works on my end, I'm sure it will work for you.

0
source share
  $(document).ready(function () { var dateNewFormat, onlyDate, today = new Date(); dateNewFormat = today.getFullYear() + '-'; if (today.getMonth().length == 2) { dateNewFormat += (today.getMonth() + 1); } else { dateNewFormat += '0' + (today.getMonth() + 1); } onlyDate = today.getDate(); if (onlyDate.toString().length == 2) { dateNewFormat += "-" + onlyDate; } else { dateNewFormat += '-0' + onlyDate; } $('#mydate').val(dateNewFormat); }); 
0
source share

All Articles