c# - 如何获取当前日期和时间?

标签 c# asp.net asp.net-mvc entity-framework date

我想查看当前日期和时间。

我做了什么:

  1. 在 Vs 2013 社区中为 asp.net mvc5 (c#) 创建了一个新项目
  2. 为我的数据库添加了一个 edmx。所以首先是数据库。
  3. 使用 Add > new scaffolded item 为我的每个数据库类添加了模型- View - Controller 。
  4. VS 为 CRUD 操作创建了 View 和 Controller 。
  5. 现在 View 中有两个字段,分别代表日期和时间。
  6. 早期的 VS 创建了简单的文本框,但我在模型中添加了注释,因此它在 View 中创建了 Datepicker 和 TimePicker。
  7. 我想要的是两个字段中的当前日期和时间。

型号:

[DataType(DataType.Date)]
public Nullable<System.DateTime> Date { get; set; }
[DataType(DataType.Time)]

查看:

    <div class="form-group">
    @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2"})
    <div class="col-md-10">

        @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control"} })
        @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.Time, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Time, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Time, "", new { @class = "text-danger" })
    </div>
</div>

Controller :

public ActionResult Create()
{
    return View();
}

These are date and time picker. i would like to have actual current date and time

这些是日期和时间选择器。我想要实际的当前日期和时间

到目前为止我尝试了什么:

使用 @value = @model.returndate = DateTime.Now;

model.returndate 总是报错。我尝试在 Controller 和 View 中使用。

使用 Viewbag.Date = DateTime.Now; 并在 View @Value = @Viewbag.Date 中没有任何反应。

最佳答案

当您使用 ModelEditorFor 显示模型属性中的日期时,您应该在返回 View 之前设置它:

public ActionResult Create()
{
    return View(new YourModel { Date = DateTime.Now } );
}

关于c# - 如何获取当前日期和时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436185/

相关文章:

c# - 如何使用 asp.net 澄清现有的 json 数据

javascript - 为什么 WCF 服务无法在托管服务器上运行?

c# - 如何在 C# 代码后面显示 PictureBox

c# - 我应该始终使用 Task.Delay 而不是 Thread.Sleep 吗?

c# - 线程池饥饿

asp.net-mvc - 如何以及在何处使用Web API2和MVC 5应用程序

asp.net-mvc - 保存浏览器 Canvas 中的图片

c# - 具有有效选择的可编辑组合框

c# - 参数依赖查找中的混淆?

c# - 如何在 VS2013 中创建一个空的 MVC 5 项目