[英]How to default a DateTime object in the EditorFor box as today's date?
I am trying to make the EditorFor bootstrap box default to today's date and be read-only, so that when the form is submitted, it will be today's date without the user having to manually enter it. 我试图使EditorFor引导框默认为今天的日期,并且为只读,以便提交表单时,它将是今天的日期,而无需用户手动输入。
I have tried some methods, but the value just remains as "mm/dd/yyyy". 我尝试了一些方法,但该值仍然保持为“ mm / dd / yyyy”。 I would like for it to say "09/05/2019" if they were submitting it today. 如果他们今天提交,我想说“ 09/05/2019”。
Here is the EditorFor box in the view 这是视图中的EditorFor框
<div class="form-group">
@Html.LabelFor(model => model.postDate, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.postDate, new { htmlAttributes = new { @value = DateTime.Today.ToString("mm/dd/yyyy"), @readonly = "readonly" } })
@Html.ValidationMessageFor(model => model.postDate, "", new { @class = "text-danger" })
</div>
</div>
And here is the attribute in the model 这是模型中的属性
[DataType(DataType.Date)]
public DateTime postDate { get; set; }
How can I get this to just be a box that shows today's date in the preferred format? 我如何才能将其变成仅以首选格式显示今天日期的框?
Try this: 尝试这个:
@Html.TextBoxFor(m => m.postDate, new { @Value = DateTime.Today.ToString("MM/dd/yyyy"), @readonly = "readonly" })
Notice: 注意:
MM
in the format MM
格式 @Value
parameter @Value
参数的大写 A different method is necessary because if you look at the signature of EditorFor
, it does not allow passing of HTML attributes. 需要使用另一种方法,因为如果您查看EditorFor
的签名 ,则该方法不允许传递HTML属性。
The MM
is the correct way of displaying the two digit month (as opposed to minutes). MM
是显示两位数月份(而不是分钟)的正确方法。
Capitalization seems necessary for @Value
. 大写似乎@Value
必要。 A lower case @value
does not work for some reason. 由于某种原因,小写的@value
无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.