IT虾米网

javascript之设置输入类型=日期

sxdcgaq8080 2025年02月15日 程序员 52 0

非常感谢您的宝贵时间

我的问题是如何设置日期类型的值输入?

@Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control", @type = "date" } }) 

它出现在 Run 之后

<input class="form-control text-box single-line" data-val="true" data-val-date="The field Date must be a date." data-val-required="The Date field is required." id="StartDate" name="StartDate" type="date" value=""> 

我用这种方式编写了一些代码

$(document).ready(function () { 
    debugger; 
    var date = $('#StartDate').val(); 
    var dt = new Date(date); 
    var day = parseInt(dt.getDate()); 
    var month = parseInt(dt.getMonth() + 1); 
    var year = parseInt(dt.getFullYear()); 
 
    if (day < 10) { day = '0' + day } 
    if (month < 10) { month = '0' + month } 
    var setDate = year + '-' + month + '-' + day; 
 
    $('#StartDate').val(setDate); 
}); 

当程序运行时,我看到调试器屏幕上的值为 string.empty

var date = ""; 

我还尝试再次删除格式错误的下部。

var dt = new Date(date); 

但我没有工作。 如果有人知道这个问题的答案 我真的需要帮助 终于看到数据了,但是 由于格式不同,值未显示。 此所需格式(yyyy-MM-dd)

谢谢大家。

请您参考如下方法:

您的脚本是不必要的,因为属性 StartDate 是一个可为空的 DateTime? 并且没有值(您的 html 有 value="" ) 那么 var dt = new Date(date); 将返回 Invalid date 因为 var date = $('#StartDate').val(); code> 返回 null 并且脚本失败。

例如,在将模型传递给 View 之前,您需要在 Controller 中设置 StartDate 的值

var model = new MyModel() { StartDate = DateTime.Today }; 
return View(model); 

这将在输入中显示今天的日期。

为了显示所需的格式,可以添加DisplayFormatAttribute

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] 
[DataType(DataType.Date)] 
public DateTime? StartDate { get; set; } 

请注意,添加 DataTypeAttribute 意味着您可以在 EditorFor() 方法中省略 type="date",因为它将由方法

或者,您可以省略这两个属性并使用

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!