Background
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:
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:
After creating the ASP.NET MVC project, the preceding folder structure and files are added into the project by default, so let us learn about them in brief as in the following:
- App_Start folder
This folder contains the application configuration details such as routing, authentication, filtering of URL and so on.
- Controller
This folder contains the controller and their methods. The controller is responsible for processing the user request and return output as a view.
- Models
This folder contains the entities or properties used to store the input values.
- View
This folder contains the UI pages including shared page, .CSHTMl, .VBHTML, HTML,aspx pages that show the output to the end user.
I hope you have understood folder structure in brief.
Step 2
Step 2
Now let us delete all the existing views, models and controller folder files. We will create it again step-by-step so that it is easier for us to understand. After deleting the existing files the Solution Explorer will look as in the following:
Step 3
Now to create the Model.
Add the new class by right-clicking on the Model folder and provide the name as EmpModel:
Now declare the properties in the EmpModel class with a DataAnnotations attribute to validate the values assigned to the properties. It is the same as get and set properties as we used in normal applications. After declaring the properties the EmpModel class will look as in the following.
EmpModel.cs
- 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;
- }
- }
- }
Step 4
Now to create the Controller.
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:
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:
After clicking on the Add button the following default code will be added into the controller class that returns an empty view:
- public class EmpController : Controller
- {
- //
- // GET: /EMP1/
- public ActionResult Index()
- {
- return View();
- }
- }
- public class EmpController : Controller
- {
- public ActionResult AddNewEmployee(EmpModel Emp)
- {
- return View();
-
- }
- }
Step 5
Now to add a View. Now that we have created the Controller, let us create the view for the AddNewEmployee action method. Right-click near to the ActionResult method definition and click "Add View...:".
Then use the following procedure:
- 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")
- }
Now we have created the model, view and controller. After adding all these things the Solution Explorer will look like the following:
Step 6
Now to configure the default routing. Run the application, then you will get the following error.
The preceding error occured because we did not configure the default routing specifying the page to be shown by default after the user visits the application. To configure it find RouteConfig.cs under App_Start folder:
Now write the following code in the RouteConfing.cs file:
- 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 }
- );
- }
- }
In the preceding code in the defaults section:
- EMP: our controller name
- AddNewEmployee: our action (method) name
- Id: optional parameter for the action (method)
Step 7
Now run the application. On pressing F5 the following page will open and try to click on the Save details button by entering invalid data; it shows the following error:
Now our model validated successfully depending on our set validation in the model class.
Step 8
Create the table in the database. To store the preceding form details in the database create the following table:
I hope you have created the same table as above.
Step 9
Create a Stored Procedure. To insert the data into the table, create the following Stored Procedure.
- 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
Step 10
Configure the AddEmployee action method. To insert the data into the database write the following code in the controller:
- ///<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();
-
- }
Step 11
Insert valid data and submit. Insert the valid data into the form and press the Save button then after saving the details the following message will be shown:
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();
- }
- }
- }
Now let us confirm the details in the database table:
Now from the preceding table records the record is inserted successfully.
Note:
- 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.
Summary
My next article explains the types of controllers in MVC. I hope this article is useful for all readers. If you have any suggestion then please contact me.

Vithal WadjePosted Aug 27, 2015, 1:20 AM
great...
Upendra Pratap ShahiPosted Aug 27, 2015, 12:13 AM
now working fine Vithal Wadje sir
Vithal WadjePosted Aug 26, 2015, 11:43 AM
Thanks Pankaj Kumar Choudhary sir
Vithal WadjePosted Aug 26, 2015, 11:43 AM
Thanks sreenivasa k sir
Vithal WadjePosted Aug 26, 2015, 11:43 AM
Upendra Pratap Shahi sir,downloading working fine at my side ,let me know what issue your are facing
Pankaj Kumar ChoudharyPosted Aug 25, 2015, 9:32 PM
Nice Explain Sir.....
sreenivasa kPosted Aug 25, 2015, 1:14 PM
excellent
Upendra Pratap ShahiPosted Aug 25, 2015, 1:04 PM
download not working sir..
Vithal WadjePosted Aug 25, 2015, 12:32 PM
Thanks Jeetendra Gund sir
Vithal WadjePosted Aug 25, 2015, 12:32 PM
Thanks Upendra Pratap Shahi sir
Vithal WadjePosted Aug 25, 2015, 12:29 PM
Thanks Vaikesh K P sir
Vithal WadjePosted Aug 25, 2015, 12:29 PM
Thanks Gowtham K sir
Vithal WadjePosted Aug 25, 2015, 12:29 PM
Thanks Manish Kumar Choudhary sir
Jeetendra GundPosted Aug 25, 2015, 11:50 AM
Welcome back sir
Upendra Pratap ShahiPosted Aug 25, 2015, 11:26 AM
nice sir..
Shridhar SharmaPosted Aug 25, 2015, 10:31 AM
nice article sir..thanks for sharing
Karthikeyan KPosted Aug 25, 2015, 9:58 AM
Good one sir...Thanks for share
RakeshPosted Aug 25, 2015, 9:46 AM
Good one sir
Nilesh JadavPosted Aug 25, 2015, 9:43 AM
Nice one sir ! I am learning MVC too and it really help me out
Rajeesh MenothPosted Aug 25, 2015, 9:34 AM
Good Explanation :) ..Thank you for sharing....
Vaikesh K PPosted Aug 25, 2015, 9:17 AM
Nice Work
Gowtham KPosted Aug 25, 2015, 8:58 AM
Good one
Manish Kumar ChoudharyPosted Aug 25, 2015, 8:54 AM
Nice one.