Creating an ASP.NET MVC Application


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:

  1. "Start" -> "All Programs" -> "Microsoft Visual Studio 2010".

  2. "File" -> "New" -> "Project..." then select "C#" -> "ASP.NET MVC 4 Application" then choose internet application.

  3. Provide the website a name as you wish and specify the location.

  4. 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

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.
  1. using System.ComponentModel.DataAnnotations;  
  3. namespace InsertingDataintoDatabaseUsingMVC.Models  
  4. {  
  5.     public class EmpModel  
  6.     {  
  7.        [Display(Name="First Name")]  
  8.        [Required (ErrorMessage="First Name is required.")]  
  9.        public string FName  
  10.         {  
  11.             get;  
  12.             set;  
  13.         }  
  14.          [Display(Name = "Middle Name")]  
  15.         public string MName  
  16.         {  
  17.              getset;   
  19.         }  
  20.        [Display(Name = "Last Name")]  
  21.        [Required(ErrorMessage = "Last Name is required.")]  
  22.         public string LName  
  23.         {   
  24.              getset;  
  25.          }  
  27.        [Display(Name = "Email Address")]  
  28.        [DataType(DataType.EmailAddress,ErrorMessage="Invalid emaild address")]  
  29.        [Required(ErrorMessage = "Emailld is required.")]  
  30.         public string EmailId  
  31.         {   
  32.            getset;   
  33.        }  
  34.     }  

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.
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:
After clicking on the Add button the following default code will be added into the controller class that returns an empty view:
  1. public class EmpController : Controller  
  2. {  
  3.     //  
  4.     // GET: /EMP1/  
  6.     public ActionResult Index()  
  7.     {  
  8.         return View();  
  9.     }  

Now remove the preceding Index Action method from the preceding Empcontroller class and add the following Action method named AddNewEmployee and the EmpModel reference:
  1.  public class EmpController : Controller  
  2.  {  
  3.      public ActionResult AddNewEmployee(EmpModel Emp)  
  4.      {  
  6.         return View();                            
  9.        }                                                      

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:
  1. 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.

  2. Choose one of the view engines from the given dropdownlist that are Razor or Aspx ,we have selected the Razor view engine.

  3. Check the checkBox to create a strongly-typed view.

  4. Now choose the model class for a strongly-typed view from the given dropdownlist. In our example we have choosen EmpModel that we created.

  5. 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.

  6. Check the References script libraries checkBox that will add jQuery libraries to validate the model input values during execution.

  7. Now check the user layout or master page layout checkBox that will add a shared page that provides a consistent look across the applications.

  8. Choose the view using the browse button of the following window. In our example we have selected _Layout.cshtml.

  9. 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:
  1. @model InsertingDataintoDatabaseUsingMVC.Models.EmpModel  
  3. @{  
  4.     ViewBag.Title = "Add Employee";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  8. <h2>AddNewEmployee</h2>  
  10. @using (Html.BeginForm()) {  
  11.     @Html.ValidationSummary(true)  
  13.     <fieldset>  
  14.         <legend>EmpModel</legend>  
  16.         <div class="editor-label">  
  17.             @Html.LabelFor(model => model.FName)  
  18.         </div>  
  19.         <div class="editor-field">  
  20.             @Html.EditorFor(model => model.FName)  
  21.             @Html.ValidationMessageFor(model => model.FName)  
  22.         </div>  
  24.         <div class="editor-label">  
  25.             @Html.LabelFor(model => model.MName)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.EditorFor(model => model.MName)  
  29.             @Html.ValidationMessageFor(model => model.MName)  
  30.         </div>  
  32.         <div class="editor-label">  
  33.             @Html.LabelFor(model => model.LName)  
  34.         </div>  
  35.         <div class="editor-field">  
  36.             @Html.EditorFor(model => model.LName)  
  37.             @Html.ValidationMessageFor(model => model.LName)  
  38.         </div>  
  40.         <div class="editor-label">  
  41.             @Html.LabelFor(model => model.EmailId)  
  42.         </div>  
  43.         <div class="editor-field">  
  44.             @Html.EditorFor(model => model.EmailId)  
  45.             @Html.ValidationMessageFor(model => model.EmailId)  
  46.         </div>  
  48.         <p>  
  49.             <input type="submit" value="Save details" />  
  50.         </p>  
  51.     </fieldset>  
  52. }  
  53. @if (ViewBag.Message != null)  
  54. {  
  55.    <span style="color:Green">@ViewBag.Message</span>  
  56. }  
  59. @section Scripts {  
  60.     @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:
  1. public class RouteConfig  
  2.    {  
  3.        public static void RegisterRoutes(RouteCollection routes)  
  4.        {  
  5.            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  7.            routes.MapRoute(  
  8.                name: "Default",  
  9.                url: "{controller}/{action}/{id}",  
  10.                defaults: new { controller = "EMP", action = "AddNewEmployee", id = UrlParameter.Optional }  
  11.            );  
  12.        }  
  13.    } 
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.
  1. Create Procedure InsertData  
  2. (  
  3. @FName varchar(50),  
  4. @MName varchar(50),  
  5. @LName varchar(50),  
  6. @EmailId  varchar(50)  
  7. )  
  8. as begin  
  10. Insert into Employee (FName,MName,LName,EmailId ) values(@FName,@MName,@LName,@EmailId )  
  11. End 
Step 10
Configure the AddEmployee action method. To insert the data into the database write the following code in the controller:
  1. ///<summary>  
  2.      ///Action method which  
  3.      ///insert the data into database by capturing  
  4.      ///Model values which comes from user as input  
  5.      ///</summary>  
  6.      public ActionResult AddNewEmployee(EmpModel Emp)  
  7.      {  
  8.         //To Prevent firing validation error on first page Load  
  10.          if (ModelState.IsValid)  
  11.          {  
  12.              connection();  
  13.              SqlCommand com = new SqlCommand("InsertData", con);  
  14.              com.CommandType = CommandType.StoredProcedure;  
  15.              com.Parameters.AddWithValue("@FName", Emp.FName);  
  16.              com.Parameters.AddWithValue("@MName", Emp.MName);  
  17.              com.Parameters.AddWithValue("@LName", Emp.LName);  
  18.              com.Parameters.AddWithValue("@EmailId", Emp.EmailId);