There are many ways to insert data into a database using ASP.NET MVC, but in this example we use a simple technique to insert data into a database using ASP.NET MVC. I have written this article focusing on beginners so they can understand the basics of MVC. Please read my previous article using the following link:
Step 1
Now let us start with a step-by-step approach from the creation of simple MVC application as in the following:
- “Start” -> “All Programs” -> “Microsoft Visual Studio 2010”.
- “File” -> “New” -> “Project…” then select “C#” -> “ASP.NET MVC 4 Application” then choose internet application.
- Provide the website a name as you wish and specify the location.
- Now after adding the MVC project, the Solution Explorer will look like the following:
- App_Start folder
- Controller
- Models
- View
Step 2
Step 3
- using System.ComponentModel.DataAnnotations;
- namespace InsertingDataintoDatabaseUsingMVC.Models
- {
- public class EmpModel
- {
- [Display(Name=“First Name”)]
- [Required (ErrorMessage=“First Name is required.”)]
- public string FName
- {
- get;
- set;
- }
- [Display(Name = “Middle Name”)]
- public string MName
- {
- get; set;
- }
- [Display(Name = “Last Name”)]
- [Required(ErrorMessage = “Last Name is required.”)]
- public string LName
- {
- get; set;
- }
- [Display(Name = “Email Address”)]
- [DataType(DataType.EmailAddress,ErrorMessage=“Invalid emaild address”)]
- [Required(ErrorMessage = “Emailld is required.”)]
- public string EmailId
- {
- get; set;
- }
- }
- }
The attributes you have seen on each property is included in the namespace System.ComponentModel.DataAnnotations that validates the input values at the client side as well as the server side at the same time time as using the jQuery library files. We will learn it in detail in my next article. I hope you have understood the concept of model.
To create the controller, right-click on the Controller folder and click on Add new controller. It shows the following window, provide a name for the controller with the suffix controller and then choose empty MVC controller from templates as in the following screenshot:
- public class EmpController : Controller
- {
- //
- // GET: /EMP1/
- public ActionResult Index()
- {
- return View();
- }
- }
Now remove the preceding Index Action method from the preceding Empcontroller class and add the following Action method named AddNewEmployee and the EmpModel reference:
- public class EmpController : Controller
- {
- public ActionResult AddNewEmployee(EmpModel Emp)
- {
- return View();
- }
- }
- Provide the view name in the free text area as shown in the following window. By default the view is created with the name ActionResult method.
- Choose one of the view engines from the given dropdownlist that are Razor or Aspx ,we have selected the Razor view engine.
- Check the checkBox to create a strongly-typed view.
- Now choose the model class for a strongly-typed view from the given dropdownlist. In our example we have choosen EmpModel that we created.
- Choose the Scaffold template that will create an automated UI depending on the model class. In our example we have chosen to create a template.
- Check the References script libraries checkBox that will add jQuery libraries to validate the model input values during execution.
- Now check the user layout or master page layout checkBox that will add a shared page that provides a consistent look across the applications.
- Choose the view using the browse button of the following window. In our example we have selected _Layout.cshtml.
- Click on the Add button.
Now after clicking on the Add button it creates the following view with a rich UI design. The following default code gets generated in the view:
- @model InsertingDataintoDatabaseUsingMVC.Models.EmpModel
- @{
- ViewBag.Title = “Add Employee”;
- Layout = “~/Views/Shared/_Layout.cshtml”;
- }
- <h2>AddNewEmployee</h2>
- @using (Html.BeginForm()) {
- @Html.ValidationSummary(true)
- <fieldset>
- <legend>EmpModel</legend>
- <div class=“editor-label”>
- @Html.LabelFor(model => model.FName)
- </div>
- <div class=“editor-field”>
- @Html.EditorFor(model => model.FName)
- @Html.ValidationMessageFor(model => model.FName)
- </div>
- <div class=“editor-label”>
- @Html.LabelFor(model => model.MName)
- </div>
- <div class=“editor-field”>
- @Html.EditorFor(model => model.MName)
- @Html.ValidationMessageFor(model => model.MName)
- </div>
- <div class=“editor-label”>
- @Html.LabelFor(model => model.LName)
- </div>
- <div class=“editor-field”>
- @Html.EditorFor(model => model.LName)
- @Html.ValidationMessageFor(model => model.LName)
- </div>
- <div class=“editor-label”>
- @Html.LabelFor(model => model.EmailId)
- </div>
- <div class=“editor-field”>
- @Html.EditorFor(model => model.EmailId)
- @Html.ValidationMessageFor(model => model.EmailId)
- </div>
- <p>
- <input type=“submit” value=“Save details” />
- </p>
- </fieldset>
- }
- @if (ViewBag.Message != null)
- {
- <span style=“color:Green”>@ViewBag.Message</span>
- }
- @section Scripts {
- @Scripts.Render(“~/bundles/jqueryval”)
- }
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
- routes.MapRoute(
- name: “Default”,
- url: “{controller}/{action}/{id}”,
- defaults: new { controller = “EMP”, action = “AddNewEmployee”, id = UrlParameter.Optional }
- );
- }
- }
- EMP: our controller name
- AddNewEmployee: our action (method) name
- Id: optional parameter for the action (method)
- Create Procedure InsertData
- (
- @FName varchar(50),
- @MName varchar(50),
- @LName varchar(50),
- @EmailId varchar(50)
- )
- as begin
- Insert into Employee (FName,MName,LName,EmailId ) values(@FName,@MName,@LName,@EmailId )
- End
- ///<summary>
- ///Action method which
- ///insert the data into database by capturing
- ///Model values which comes from user as input
- ///</summary>
- public ActionResult AddNewEmployee(EmpModel Emp)
- {
- //To Prevent firing validation error on first page Load
- if (ModelState.IsValid)
- {
- connection();
- SqlCommand com = new SqlCommand(“InsertData”, con);
- com.CommandType = CommandType.StoredProcedure;
- com.Parameters.AddWithValue(“@FName”, Emp.FName);
- com.Parameters.AddWithValue(“@MName”, Emp.MName);
- com.Parameters.AddWithValue(“@LName”, Emp.LName);
- com.Parameters.AddWithValue(“@EmailId”, Emp.EmailId);
- con.Open();
- int i = com.ExecuteNonQuery();
- con.Close();
- if (i >= 1)
- {
- ViewBag.Message = “New Employee Added Successfully”;
- }
- }
- ModelState.Clear();
- return View();
- }
Now the complete code of Emp controller will look as in the following:
- using System.Web.Mvc;
- using InsertingDataintoDatabaseUsingMVC.Models;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.Data;
- namespace InsertingDataintoDatabaseUsingMVC.Controllers
- {
- public class EmpController : Controller
- {
- private SqlConnection con;
- private void connection()
- {
- string constr = ConfigurationManager.ConnectionStrings[“getconn”].ToString();
- con = new SqlConnection(constr);
- }
- ///<summary>
- ///Action method which
- ///insert the data into database by capturing
- ///Model values which comes from user as input
- ///</summary>
- public ActionResult AddNewEmployee(EmpModel Emp)
- {
- //To Prevent firing validation error on first page Load
- if (ModelState.IsValid)
- {
- connection();
- SqlCommand com = new SqlCommand(“InsertData”, con);
- com.CommandType = CommandType.StoredProcedure;
- com.Parameters.AddWithValue(“@FName”, Emp.FName);
- com.Parameters.AddWithValue(“@MName”, Emp.MName);
- com.Parameters.AddWithValue(“@LName”, Emp.LName);
- com.Parameters.AddWithValue(“@EmailId”, Emp.EmailId);
- con.Open();
- int i = com.ExecuteNonQuery();
- con.Close();
- if (i >= 1)
- {
- ViewBag.Message = “New Employee Added Successfully”;
- }
- }
- ModelState.Clear();
- return View();
- }
- }
- }
- Configure the database connection in the web.config file depending on your database server location.
- Download the Zip file of the sample application for a better understanding .
- Since this is a demo, it might not be using proper standards so imrove it depending on your skills
- This application is created completely focusing on beginners.