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;
- }
- }
- }
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();
- }
- }
- public class EmpController : Controller
- {
- public ActionResult AddNewEmployee(EmpModel Emp)
- {
- return View();
-
- }
- }
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...:".
- 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 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 }
- );
- }
- }
- 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.
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.