Steven
asked on
create datetime stamp on database
Good afternoon,
I would like to add a date and time when saving to my database (like a date time stamp) but I don't know how to set the a default date (date.now) and then pass it to my controller when I submit. As I stated in my previous post I'm new to MVC so I appreciate your patience.
model
controller
I would like to add a date and time when saving to my database (like a date time stamp) but I don't know how to set the a default date (date.now) and then pass it to my controller when I submit. As I stated in my previous post I'm new to MVC so I appreciate your patience.
model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace BiciPublica.Models
{
public class Usuario
{
public int Id { get; set; }
[Required]
[StringLength(80)]
public string Nombres { get; set; }
[Required]
[StringLength(40)]
[Display(Name ="Primer apellido")]
public string PrimerApellido { get; set; }
[Required]
[StringLength(40)]
[Display(Name = "Segundo apellido")]
public string SegundoApellido { get; set; }
[Required]
[StringLength(30)]
public string Cedula { get; set; }
[Required]
[Display(Name = "Fecha nacimiento ")]
public DateTime FechaNacimiento { get; set; }
[Required]
[StringLength(5)]
public string Rh { get; set; }
[Required]
[StringLength(10)]
public char Genero { get; set; }
[Required]
[StringLength(200)]
[Display(Name = "Dirección")]
public string Direccion { get; set; }
[Required]
[StringLength(200)]
[Display(Name = "Barrio")]
public string Barrio { get; set; }
public Municipio Municipio { get; set; }
[Display(Name = "Municipio")]
public int MunicipioId { get; set; }
[Display(Name ="Telefono fijo")]
public string TelefonoFijo { get; set; }
[Required]
[StringLength(30)]
public string Celular { get; set; }
[Required]
[StringLength(254)]
public string Correo { get; set; }
public string Foto { get; set; }
public string ImagenCC { get; set; }
public string NumeroIdServicio { get; set; }
[Required]
public bool ResidenteAMB { get; set; }
[Required]
public DateTime FechaInicioRegistro { get; set; }
[Required]
public Boolean Validado { get; set; }
public DateTime? FechaFinalizaRegistro { get; set; }
public int Pin { get; set; }
}
}
controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;
namespace BiciPublica.Models
{
public class Usuario
{
public int Id { get; set; }
[Required]
[StringLength(80)]
public string Nombres { get; set; }
[Required]
[StringLength(40)]
[Display(Name ="Primer apellido")]
public string PrimerApellido { get; set; }
[Required]
[StringLength(40)]
[Display(Name = "Segundo apellido")]
public string SegundoApellido { get; set; }
[Required]
[StringLength(30)]
public string Cedula { get; set; }
[Required]
[Display(Name = "Fecha nacimiento ")]
public DateTime FechaNacimiento { get; set; }
[Required]
[StringLength(5)]
public string Rh { get; set; }
[Required]
[StringLength(10)]
public string Genero { get; set; }
[Required]
[StringLength(200)]
[Display(Name = "Dirección")]
public string Direccion { get; set; }
[Required]
[StringLength(200)]
[Display(Name = "Barrio")]
public string Barrio { get; set; }
public Municipio Municipio { get; set; }
[Display(Name = "Municipio")]
public int MunicipioId { get; set; }
[Display(Name ="Telefono fijo")]
public string TelefonoFijo { get; set; }
[Required]
[StringLength(30)]
public string Celular { get; set; }
[Required]
[StringLength(254)]
public string Correo { get; set; }
public string Foto { get; set; }
public string ImagenCC { get; set; }
public string NumeroIdServicio { get; set; }
[Required]
public bool ResidenteAMB { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[DefaultValue("getutcdate()")]
public DateTime FechaInicioRegistro { get; set; }
[DefaultValue(false)]
[Required]
public Boolean Validado { get; set; }
public DateTime? FechaFinalizaRegistro { get; set; }
public int Pin { get; set; }
}
}
and my view@model BiciPublica.ViewModels.NuevoUsuarioViewModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="header-page-bici">
<div class="container">
<h1>Inscripción </h1>
<p>Ingresa tu información para poder iniciar a utilizar los servicios de Ponte BICI.</p>
</div>
</div>
@using (Html.BeginForm("Crear", "Usuario"))
{
@Html.AntiForgeryToken()
<div class="container">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.Nombres)
@(Html.Kendo().TextBoxFor(m => m.Usuario.Nombres)
.Name("Nombres")
.Value("William")
.HtmlAttributes(new { placeholder = "Nombres", required = "required", validationmessage = "Enter {0}", style = "width:100%" })
)
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.PrimerApellido)
@(Html.Kendo().TextBoxFor(m => m.Usuario.PrimerApellido)
.Name("PrimerApellido")
.Value("Wallace")
.HtmlAttributes(new { placeholder = "Primer Apellido", required = "required", validationmessage = "Enter {0}", style = "width:100%" })
)
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.SegundoApellido)
@(Html.Kendo().TextBoxFor(m => m.Usuario.SegundoApellido)
.Name("SegundoApellido")
.Value("Gil")
.HtmlAttributes(new { placeholder = "Segundo Apellido", required = "required", validationmessage = "Enter {0}", style = "width:100%" })
)
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.Cedula)
@(Html.Kendo().TextBoxFor(m => m.Usuario.Cedula)
.Name("Cedula")
.Value("1325854")
.HtmlAttributes(new { placeholder = "No signos de puntuacion", required = "required", pattern = "\\d+", validationmessage = "Enter {0}", style = "width:100%" })
)
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.FechaNacimiento)
@(Html.Kendo().DatePickerFor(m => m.Usuario.FechaNacimiento)
.Name("FechaNacimiento")
.Value("1/07/1965")
.HtmlAttributes(new { style = "width: 100%", required = "required", }) )
</div>
<div class="form-group col-md-4">
<div class="editor-field">
@Html.DropDownList("Genero", new List<SelectListItem>
{
new SelectListItem{ Text="Male", Value="Male"},
new SelectListItem{ Text="Female", Value="Female"}
}, "--- Select ---", new { @class = "form-control" })
</div>
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.Rh)
@(Html.Kendo().TextBoxFor(m => m.Usuario.Rh)
.Name("RH")
.Value("O+")
.HtmlAttributes(new { placeholder = "ej. O+", required = "required", validationmessage = "Enter {0}", style = "width:100%" })
)
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.Direccion)
@(Html.Kendo().TextBoxFor(m => m.Usuario.Direccion)
.Name("Direccion")
.Value("cll 12 # 5 -315")
.HtmlAttributes(new { placeholder = "", required = "required", validationmessage = "Ingrese {0}", style = "width:100%" })
)
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.Barrio)
@(Html.Kendo().TextBoxFor(m => m.Usuario.Barrio)
.Name("Barrio")
.Value("1/07/1965")
.HtmlAttributes(new { placeholder = "Nombre del Barrio", required = "required", validationmessage = "Enter {0}", style = "width:100%" })
)
</div>
@*<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.MunicipioId)
@(Html.Kendo().DropDownListFor(m => m.Usuario.MunicipioId)
.BindTo(new SelectList(Model.Municipios, "Id", "Nombre"))
.HtmlAttributes(new { required = "required", style = "width: 100%" })
)
</div>*@
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.TelefonoFijo)
@(Html.Kendo().TextBoxFor(m => m.Usuario.TelefonoFijo)
.Name("TelefonoFijo")
.Value("6553265")
.HtmlAttributes(new { placeholder = "ej. 6356556", validationmessage = "Enter {0}", style = "width:100%" })
)
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.Celular)
@(Html.Kendo().TextBoxFor(m => m.Usuario.Celular)
.Name("Celular")
.Value("3172266756")
.HtmlAttributes(new { required = "required", placeholder = "Ingrese numero telefonico", pattern = "\\d{10}", type = "tel", style = "width:100%;" }) )
@Html.ValidationMessageFor(model => model.Usuario.Celular, "", new { @class = "text-danger" })
</div>
<div class="form-group col-md-4">
@Html.LabelFor(model => model.Usuario.Correo)<br />
@(Html.Kendo().TextBox()
.Name("Correo")
.Value("steve_724@hotmail.com")
.HtmlAttributes(new { placeholder = "ej: minombre@ejemplo.net", required = "required", type = "email", data_email_msg = "Formato de correo incorrecto.", style = "width: 100%;" })
)
</div>
<div class="checkbox col-md-4" style="padding-top:20px;">
<label>
@*@Html.CheckBoxFor(model => model.Usuario.ResidenteAMB)Residente Area Metropolitana Bucaramanga?*@
</label>
@Html.ValidationMessageFor(model => model.Usuario.ResidenteAMB, "", new { @class = "text-danger" })
</div>
<div class="row">
<div class="checkbox col-md-12" style="padding-top:20px;">
<label>
@*@Html.CheckBoxFor(model => model.Usuario.ResidenteAMB)Confirmo que he leído y acepto el contrato de uso PonteBICI*@
</label>
@*@Html.ValidationMessageFor(model => model.Usuario.ResidenteAMB, "", new { @class = "text-danger" })*@
</div><br />
@*Confirmo que he leído y acepto el contrato de uso PonteBICI.
Confirmo que tengo tarjeta Metrolinea
Confirmo que tengo cobertura de salud*@
</div>
<div class="form-group col-md-12 text-center">
<button type="submit" class="btn btn-default" >Inscribirse</button>
</div>
</div>
}
@*<script>
$(function () {
var validator = $("#usuarioForm").kendoValidator().data("kendoValidator");
//var status = $(".status");
$("form").submit(function (event) {
event.preventDefault();
//if (validator.validate()) {
// status.text("Hooray! Your tickets has been booked!")
// .removeClass("invalid")
// .addClass("valid");
//} else {
// status.text("Oops! There is invalid data in the form.")
// .removeClass("valid")
// .addClass("invalid");
//}
});
});
</script>*@
You can add the default value in the table so you don't need to perform any code (it will add automatically the current date when inserting a row). Just open a new query window in the SSMS and type the following (provide the correct table and column name):
ALTER TABLE tableName
ADD CONSTRAINT TableDefaultDate
DEFAULT GETDATE() FOR columnName;
ASKER
Thanks for the responses, I understand I can change that in the database, but how can I change it if I'm using code first?, I would like to avoid making changes directly in the DB (SQL). Also I want to save two dates one when the record is created for the first time (which should work using getdate when the record is created), but the other date i want to save is when the record is updated, how can I add that time stamp?
thanks
thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
add a default "SQL server: getdate()" / "Oracle: Sysdate" value to the column and dont pass anything...