用户在数据库中插入数据时如何插入当前日期和时间

时间:2017-06-13 13:32:03

标签: asp.net-mvc-4

我正在尝试将数据插入数据库。我基本上试图获取当前日期,我也隐藏了该特定字段(“更新日期”),因为我确实希望用户看到。现在我想要的是每当我向数据库插入一些数据时,应自动插入数据库。< / p>

控制器

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(StoreImageCreateVM StoreImageVM)
    {
        if (ModelState.IsValid)
        {
            try
            {
                StoreImageLogic.Insert(StoreImageVM);
            }
            catch (Exception e) 
            {
                TempData["Failure"] = "Creation Failed. Image too large.";
                return View(StoreImageVM);
            }
            TempData["Success"] = "Creation Successful";
            return RedirectToAction("Index", new { id = StoreImageVM.StoreID });
        }
  return View(StoreImageVM);
    }

savechangesmethod

 public bool Insert(StoreImageCreateVM imageVM)
    {
        StoreImage image = new StoreImage();

        image.StoreID = imageVM.StoreID;
        image.ImageDescription = imageVM.Description;
        image.UploadDate = imageVM.uploadDate;



        //Upload the file
        string path = AppDomain.CurrentDomain.BaseDirectory + @"Content\Uploads";            
        string filename = imageVM.File.FileName;
        string fullPath = Path.Combine(path, filename);

        imageVM.File.SaveAs(fullPath);

        //Set imageURL
        string serverFilePath = @"\Content\Uploads\";
        image.FullFilePath = serverFilePath + filename;
        image.Active = true;

        return base.Insert(image).StoreImageID != 0;
    }
}

1 个答案:

答案 0 :(得分:0)

我只是添加以使用DateTime.Now方法更改savechanges方法。见下文。

        public bool Insert(StoreImageCreateVM imageVM)
    {
        StoreImage image = new StoreImage();

        image.StoreID = imageVM.StoreID;
        image.ImageDescription = imageVM.Description;
        image.UploadDate = DateTime.Now;



        //Upload the file
        string path = AppDomain.CurrentDomain.BaseDirectory + @"Content\Uploads";            
        string filename = imageVM.File.FileName;
        string fullPath = Path.Combine(path, filename);

        imageVM.File.SaveAs(fullPath);

        //Set imageURL
        string serverFilePath = @"\Content\Uploads\";
        image.FullFilePath = serverFilePath + filename;
        image.Active = true;

        return base.Insert(image).StoreImageID != 0;
    }
}

}