Objective: It is necessary to implement automatic insertion of the current date and time when adding an entry to the table (IDStudent).

public class Students { [Key] [HiddenInput(DisplayValue = false)] public int StudentsId { get; set; } public string IDStudent { get; set; } public string Name { get; set; } public string Notes { get; set; } public string datetime { get; set; } /* **???** */ } 

Data in db is already there and you just need to add or create a new IDStudent.

  @using (Html.BeginForm()) { @Html.TextBoxFor(m => m.IDStudent, new { @class = "form-control"}) @Html.ValidationMessage("IDStudent") <div class=""> <input type="submit" value="Сохранить" class="btn btn-primary" /> </div> } 

When you save IDStudent, the date and time are automatically saved.

From where to get the date and time? In the controller and deliver it as a string to the database or through sql? How to implement it and how easier?

Only cognize programming and mvc. Thank you in advance for your response!

  • What approach is used? Do you use EF? - Vadim Prokopchuk

1 answer 1

This can be done in several ways:

  1. Write trigger:

     create trigger insertToStudentsTrigger on Students for insert as if @@rowcount=1 begin update Students set datetime=getdate() where id=inserted.id end 
  2. Set a default value in the database.

     [ExampleDateTime] DATETIME DEFAULT getdate() NOT NULL 

    List of functions and types for working with date and time (T-SQL)

  3. Set explicitly in your method that inserts a value into the database.

     student.datetime = DateTime.Now;