In this article I will explain with an example, how to insert Date in dd/MM/yyyy format in SQL Server Database Table using ASP.Net MVC Razor.
This article will illustrate how to insert Date in dd/MM/yyyy format in Database Table using Stored Procedures and the SQL Server DATEFORMAT command in ASP.Net MVC Razor.
Configuring Bundles and enabling Client Side Validation
Please refer the following article for complete information on how to configure Bundles and enable Client Side validation in ASP.Net MVC project.
Note: By default the validation done using Data Annotation attributes is Server Side. And hence to make it work Client Side, the Client Side validation must be enabled.
Database
I have made use of the following table Medicines with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
Stored Procedure for inserting Date in dd/MM/yyyy format
Inside the Insert_Medicine Stored Procedure, the Date parameters are of VARCHAR data type so that the Date values can be passed in dd/MM/yyyy format.
Before the INSERT statement, the DATEFORMAT command is executed with DMY option which notifies SQL Server that the values of Dates will be in dd/MM/yyyy format.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Insert_Medicine
@Name VARCHAR(50),
@ManufacturingDate VARCHAR(10),
@ExpiryDate VARCHAR(10)
AS
BEGIN
SET NOCOUNT ON;
SET DATEFORMAT DMY
INSERT INTO Medicines
VALUES(@Name, @ManufacturingDate, @ExpiryDate)
END
GO
Model
The following Model class consists of three properties to which the following validation Data Annotation attributes have been applied.
1. Required Data Annotation attribute.
2. RegularExpression Data Annotation attribute.
The RegularExpression Data Annotation attribute accepts the Regular Expression as first parameter. The Regular expression will allow only dd/MM/yyyy date format.
The Required Data Annotation and the RegularExpression Data Annotation attributes have been specified with a property Error Message with a string value. As the name suggests, this string value will be displayed to the user when the respective validation fails.
public class MedicineModel
{
[Display(Name = "Medicine Name:")]
[Required(ErrorMessage = "Required")]
public string Name { get; set; }
[Display(Name = "Manufacturing Date:")]
[Required(ErrorMessage = "Required")]
[RegularExpression(@"(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$", ErrorMessage = "Invalid date format.")]
public string ManufacturingDate { get; set; }
[Display(Name = "Expiry Date:")]
[Required(ErrorMessage = "Required")]
[RegularExpression(@"(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$", ErrorMessage = "Invalid date format.")]
public string ExpiryDate { get; set; }
}
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This action method handles the POST operation and when the form is submitted, the object of the MedicineModel class is sent to this method.
The submitted data i.e. Name, Manufacturing Date and Expiry Date are inserted into the Database using the Insert_Medicine Stored Procedure.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(MedicineModel medicine)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Insert_Medicine"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name", medicine.Name.Trim());
cmd.Parameters.AddWithValue("@ManufacturingDate", medicine.ManufacturingDate.Trim());
cmd.Parameters.AddWithValue("@ExpiryDate", medicine.ExpiryDate.Trim());
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
ModelState.Clear();
return View(new MedicineModel());
}
}
View
Inside the View, in the very first line the MedicineModel class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the View, the following three HTML Helper functions are used:-
1. Html.LabelFor – Displaying the Model property name.
2. Html.TextBoxFor – Creating a TextBox for the Model property.
3. Html.ValidationMessageFor – Displaying the Validation message for the property.
There is also Submit button which when clicked, the Form gets submitted.
The jQuery and the jQuery Validation script bundles are rendered at the end of the Model using the Scripts.Render function.
@model Date_ddMMyyyy_Insert_DB_MVC.Models.MedicineModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
.error
{
color: red;
}
</style>
</head>
<body>
@using (@Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
<tr>
<td>@Html.LabelFor(m => m.Name)</td>
<td>@Html.TextBoxFor(m => m.Name)</td>
<td>@Html.ValidationMessageFor(m => m.Name, "", new { @class = "error" })</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.ManufacturingDate)</td>
<td>@Html.TextBoxFor(m => m.ManufacturingDate)</td>
<td>@Html.ValidationMessageFor(m => m.ManufacturingDate, "", new { @class = "error" })</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.ExpiryDate)</td>
<td>@Html.TextBoxFor(m => m.ExpiryDate)</td>
<td>@Html.ValidationMessageFor(m => m.ExpiryDate, "", new { @class = "error" })</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save"/></td>
<td></td>
</tr>
</table>
}
</body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
</html>
Screenshots
Inserting Date in dd/MM/yyyy format in ASP.Net
Date inserted in Table
Downloads