MVC Razor-文本框类型日期的默认值为“当前日期"
问题描述:
我有一个Textbox
,类型为date
.我正在尝试将textbox
的默认值设置为当前日期.
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?
答
正如Stephen Muecke所说,您需要在模型上设置属性的值.
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);
您的剃刀将是:
@Html.TextBoxFor(x => x.Date, "{0:yyyy-MM-dd}", new { @class = "form-control", @type = "date"})
请注意,在使用For
方法(例如@Html.TextBoxFor()
)时,应将id
和name
属性自动分配给属性名称,因此您无需显式设置id
属性.
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.