【问题标题】:Trying to simply add a variable value to database试图简单地将变量值添加到数据库
【发布时间】:2018-12-17 06:58:27
【问题描述】:

asp.net core 的新手。我有一个数据库(让我们在 database123 中调用),其中包含表 Student。 Student 有 4 列,StudentId、StudentNameName、StudentGender 和 CreatedUtc。

通过 razor 页面向数据库添加数据没有问题。但我希望将 CreatedUtc 值插入数据库,而不是通过视图,而是通过控制器(它是创建记录的日期,应该来自 DateTime.Now.ToString 或类似的东西。

我无法确定在何处以及如何将其编码到 Create.cshtml.cs 控制器中。我认为它需要输入到公共异步任务 OnPostAsync() 中。

目前我有这个

 public async Task<IActionResult> OnPostAsync()
  {
  if (!ModelState.IsValid)
  {
   return Page();
   }
    MessageVar += $" Server time  { DateTime.Now.ToString() }"; // Get Date and Time
    _context.Student.Add(Student);
     await _context.SaveChangesAsync();
     return RedirectToPage("./Index");
    }

在上面的 CreateModel 区域,我有这个:-

   public string MessageVar { get; private set; } = "Local Server Time: ";

任何帮助将不胜感激。我知道这可能真的很简单,但就是找不到它。

提前致谢,

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    在保存您的学生之前,请设置时间。

    student.createdutc = DateTime.UtcNow;
    

    【讨论】:

    • 嗨 JayBird,我可能遗漏了一些东西,但出现了错误。 " 无法将类型 "string" 隐式转换为 "System.DateTime" "
    • 我已经更新了答案,不需要将日期设为字符串。
    • 抱歉,CreatedUtc 是模型中的 DateTime 字段。你给了我一个想法,我刚刚输入了这个Student.CreatedUtc = DateTime.Now;,没有错误。我现在正在测试。谢谢。
    • 进一步更新。由于您的字段名为 createdutc,您可以使用 UtcNow 为其分配当前 Utc 日期
    • 太棒了,JayBird,非常感谢你,伙计,太棒了!我知道会很简单,没想到会这么简单。非常感谢你,伙计。 ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 2011-07-28
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多