MVC Razor-文本框类型日期的默认值为“当前日期" [英] MVC Razor - Default Value as Current date for textbox type date

查看:146
本文介绍了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())时,应将idname属性自动分配给属性名称,因此您无需显式设置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.

这篇关于MVC Razor-文本框类型日期的默认值为“当前日期"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆