Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
Anup Avatar asked Oct 17 '14 04:10

Anup


3 Answers

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.

like image 186
ps2goat Avatar answered Nov 20 '22 11:11

ps2goat


It's better way to manage in view

@Html.TextBoxFor(x=> x.Date, new { @Value = @DateTime.Now.ToShortDateString() })
like image 30
renjith Avatar answered Nov 20 '22 12:11

renjith


<input asp-for="date" value="@DateTime.Today" type="datetime" class="form-control" />

This works for me. Remember to change 'date' according to your model.

and use this, if you need time as well

<input asp-for="date" value="@DateTime.Now" type="datetime" class="form-control" />

like image 5
Pamy Avatar answered Nov 20 '22 11:11

Pamy