MVC Razor-文本框类型日期的默认值为当前日期



我有一个类型为dateTextbox。我正在尝试将textbox的默认值设置为当前日期。

@Html.TextBoxFor(x => x.Date, new { @id = "Date", @type = "date", 
                                    @value = DateTime.Now.ToShortDateString() })

上面的行没有设置默认值。如何将默认值设置为当前日期?

正如Stephen Muecke所说,您需要在模型上设置属性的值。

// 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属性。

这是在视图中管理的更好方法

@Html.TextBoxFor(x=> x.Date, new { @Value = @DateTime.Now.ToShortDateString() })

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

这对我有用。记住根据你的型号更改"日期"。

如果你也需要时间的话,使用这个

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

在您的控制器中使用此:

MyModel model = new MyModel();
model.Date = model.date == null ? DateTime.Today : model.date;
return View(model);

在您的视图页面

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

另一个解决方案:

 @Html.TextBoxFor(model=>model.CreatedOn, new{@value= System.DateTime.Now})

它对我有效,当然对你也有效。

 $(document).ready(function () {
        var dateNewFormat, onlyDate, today = new Date();
        dateNewFormat = today.getFullYear() + '-';
        if (today.getMonth().length == 2) {
            dateNewFormat += (today.getMonth() + 1);
        }
        else {
            dateNewFormat += '0' + (today.getMonth() + 1);
        }
        onlyDate = today.getDate();
        if (onlyDate.toString().length == 2) {
            dateNewFormat += "-" + onlyDate;
        }
        else {
            dateNewFormat += '-0' + onlyDate;
        }
        $('#mydate').val(dateNewFormat);
    });

您可以在视图中使用此脚本

你的剃须刀你的剃须刀页面就像

    window.onload = function () {
        var date = new Date();
        var Mes = String(date.getMonth() + 1).padStart(2, '0');
        var Dia = String(date.getDate()).padStart(2, '0');
        var Anio = date.getFullYear();
        document.getElementById("currentDate").value = Anio + "-" + Mes + "-" + Dia;
    };
<div class="col-md-10">
                <input class="form-control text-box single-line"  id="currentDate" name="currentDate" type="date" value="">
 </div>

最新更新