CRUD Operation With ASP.NET Core MVC Using Visual Studio Code And ADO.NET

Introduction

In this article, we are going to create a web application using ASP.NET Core MVC with the help of Visual Studio Code and ADO.NET. We will be creating a sample Employee Record Management System and will be performing CRUD operation on it.

Prerequisites

  • Install .NET Core 2.0.0 or above SDK from here
  • Download and install Visual Studio Code from here
  • SQL Server 2008 or above

Creating Table and Stored Procedures

We will be using a DB table to store all the records of the employees.

Open SQL Server and use the following script to create tblEmployee table.

  1. Create table tblEmployee(        
  2.     EmployeeId int IDENTITY(1,1) NOT NULL,        
  3.     Name varchar(20) NOT NULL,        
  4.     City varchar(20) NOT NULL,        
  5.     Department varchar(20) NOT NULL,        
  6.     Gender varchar(6) NOT NULL        
  7. )     

Now, we will create stored procedures to add, delete, update, and get employee data.

To Insert an Employee Record

  1. Create procedure spAddEmployee         
  2. (        
  3.     @Name VARCHAR(20),         
  4.     @City VARCHAR(20),        
  5.     @Department VARCHAR(20),        
  6.     @Gender VARCHAR(6)        
  7. )        
  8. as         
  9. Begin         
  10.     Insert into tblEmployee (Name,City,Department, Gender)         
  11.     Values (@Name,@City,@Department, @Gender)         
  12. End     

To Update an Employee Record

  1. Create procedure spUpdateEmployee          
  2. (          
  3.    @EmpId INTEGER ,        
  4.    @Name VARCHAR(20),         
  5.    @City VARCHAR(20),        
  6.    @Department VARCHAR(20),        
  7.    @Gender VARCHAR(6)        
  8. )          
  9. as          
  10. begin          
  11.    Update tblEmployee           
  12.    set Name=@Name,          
  13.    City=@City,          
  14.    Department=@Department,        
  15.    Gender=@Gender          
  16.    where EmployeeId=@EmpId          
  17. End     

To Delete an Employee Record

  1. Create procedure spDeleteEmployee         
  2. (          
  3.    @EmpId int          
  4. )          
  5. as           
  6. begin          
  7.    Delete from tblEmployee where EmployeeId=@EmpId          
  8. End   

To View all Employees' Records

  1. Create procedure spGetAllEmployees      
  2. as      
  3. Begin      
  4.     select *      
  5.     from tblEmployee      
  6. End   

Now, our Database part has been completed. So, we will proceed to create the MVC application using Visual Studio Code.

Create the MVC Web Application

We will be creating a source project from the terminal window in Visual Studio Code. Open VS Code and navigate to View >> Integrated Terminal.

This will open the terminal window as shown in the image below.

 

Type the following sequence of commands in the terminal window. It will create our MVC application, "MvcAdoDemo".

  • mkdir MvcAdoDemo
  • cd MvcAdoDemo
  • dotnet new mvc
 

Now, open this “MvcAdoDemo” project file using VS Code. If it prompts the message "Required assets to build and debug are missing from MvcAdoDemo. Add them?", select "Yes".

 

You can observe in the Solution Explorer that we already have folders created with name Controllers, Models, and Views. We will be adding our code files to these folders only.



Adding the Model to the application

Right-click the Models folder and select "New File". Name it as Employee.csIt will create a file inside Models folder. 

 

Add one more file to Models folder. Name it as EmployeeDataAccessLayer.cs. This class will contain our database related operations.

Open Employee.cs and put the following code inside it. Since we are adding the required validators to the fields of Employee class, we need to use System.ComponentModel.DataAnnotations at the top.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.ComponentModel.DataAnnotations;    
  4. using System.Linq;    
  5. using System.Threading.Tasks;    
  6.     
  7. namespace MVCAdoDemo.Models    
  8. {    
  9.     public class Employee    
  10.     {    
  11.         public int ID { getset; }    
  12.         [Required]    
  13.         public string Name { getset; }    
  14.         [Required]    
  15.         public string Gender { getset; }    
  16.         [Required]    
  17.         public string Department { getset; }    
  18.         [Required]    
  19.         public string City { getset; }    
  20.     }    
  21. }  

Open EmployeeDataAccessLayer.cs and put the following code to handle the database operations. Make sure to put your own connection string.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Data;    
  4. using System.Data.SqlClient;    
  5. using System.Linq;    
  6. using System.Threading.Tasks;    
  7.     
  8. namespace MVCAdoDemo.Models    
  9. {    
  10.     public class EmployeeDataAccessLayer    
  11.     {    
  12.         string connectionString = "Your Connection String";    
  13.     
  14.         //To View all employees details      
  15.         public IEnumerable<Employee> GetAllEmployees()    
  16.         {    
  17.             List<Employee> lstemployee = new List<Employee>();    
  18.     
  19.             using (SqlConnection con = new SqlConnection(connectionString))    
  20.             {    
  21.                 SqlCommand cmd = new SqlCommand("spGetAllEmployees", con);    
  22.                 cmd.CommandType = CommandType.StoredProcedure;    
  23.     
  24.                 con.Open();    
  25.                 SqlDataReader rdr = cmd.ExecuteReader();    
  26.     
  27.                 while (rdr.Read())    
  28.                 {    
  29.                     Employee employee = new Employee();    
  30.     
  31.                     employee.ID = Convert.ToInt32(rdr["EmployeeID"]);    
  32.                     employee.Name = rdr["Name"].ToString();    
  33.                     employee.Gender = rdr["Gender"].ToString();    
  34.                     employee.Department = rdr["Department"].ToString();    
  35.                     employee.City = rdr["City"].ToString();    
  36.     
  37.                     lstemployee.Add(employee);    
  38.                 }    
  39.                 con.Close();    
  40.             }    
  41.             return lstemployee;    
  42.         }    
  43.     
  44.         //To Add new employee record      
  45.         public void AddEmployee(Employee employee)    
  46.         {    
  47.             using (SqlConnection con = new SqlConnection(connectionString))    
  48.             {    
  49.                 SqlCommand cmd = new SqlCommand("spAddEmployee", con);    
  50.                 cmd.CommandType = CommandType.StoredProcedure;    
  51.     
  52.                 cmd.Parameters.AddWithValue("@Name", employee.Name);    
  53.                 cmd.Parameters.AddWithValue("@Gender", employee.Gender);    
  54.                 cmd.Parameters.AddWithValue("@Department", employee.Department);    
  55.                 cmd.Parameters.AddWithValue("@City", employee.City);    
  56.     
  57.                 con.Open();    
  58.                 cmd.ExecuteNonQuery();    
  59.                 con.Close();    
  60.             }    
  61.         }    
  62.     
  63.         //To Update the records of a particluar employee    
  64.         public void UpdateEmployee(Employee employee)    
  65.         {    
  66.             using (SqlConnection con = new SqlConnection(connectionString))    
  67.             {    
  68.                 SqlCommand cmd = new SqlCommand("spUpdateEmployee", con);    
  69.                 cmd.CommandType = CommandType.StoredProcedure;    
  70.     
  71.                 cmd.Parameters.AddWithValue("@EmpId", employee.ID);    
  72.                 cmd.Parameters.AddWithValue("@Name", employee.Name);    
  73.                 cmd.Parameters.AddWithValue("@Gender", employee.Gender);    
  74.                 cmd.Parameters.AddWithValue("@Department", employee.Department);    
  75.                 cmd.Parameters.AddWithValue("@City", employee.City);    
  76.     
  77.                 con.Open();    
  78.                 cmd.ExecuteNonQuery();    
  79.                 con.Close();    
  80.             }    
  81.         }    
  82.     
  83.         //Get the details of a particular employee    
  84.         public Employee GetEmployeeData(int? id)    
  85.         {    
  86.             Employee employee = new Employee();    
  87.     
  88.             using (SqlConnection con = new SqlConnection(connectionString))    
  89.             {    
  90.                 string sqlQuery = "SELECT * FROM tblEmployee WHERE EmployeeID= " + id;    
  91.                 SqlCommand cmd = new SqlCommand(sqlQuery, con);    
  92.     
  93.                 con.Open();    
  94.                 SqlDataReader rdr = cmd.ExecuteReader();    
  95.     
  96.                 while (rdr.Read())    
  97.                 {    
  98.                     employee.ID = Convert.ToInt32(rdr["EmployeeID"]);    
  99.                     employee.Name = rdr["Name"].ToString();    
  100.                     employee.Gender = rdr["Gender"].ToString();    
  101.                     employee.Department = rdr["Department"].ToString();    
  102.                     employee.City = rdr["City"].ToString();    
  103.                 }    
  104.             }    
  105.             return employee;    
  106.         }    
  107.     
  108.         //To Delete the record on a particular employee    
  109.         public void DeleteEmployee(int? id)    
  110.         {    
  111.     
  112.             using (SqlConnection con = new SqlConnection(connectionString))    
  113.             {    
  114.                 SqlCommand cmd = new SqlCommand("spDeleteEmployee", con);    
  115.                 cmd.CommandType = CommandType.StoredProcedure;    
  116.     
  117.                 cmd.Parameters.AddWithValue("@EmpId", id);    
  118.     
  119.                 con.Open();    
  120.                 cmd.ExecuteNonQuery();    
  121.                 con.Close();    
  122.             }    
  123.         }    
  124.     }    
  125. }    

To use ADO.NET functionalities in VS code, we need to add the NuGet package reference to System.Data.SqlClient. Open MvcAdoDemo.csproj file and put the following code into it.

  1. <PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
Put this code in the location highlighted in the image below.

 

Adding the Controller to the application

Right-click on Controllers folder and select "New File". Name it as EmployeeController.cs. It will create a new file inside Controllers folder.



Now, our EmployeeController has been created. We will put all our business logic on this Controller.

Adding Views to the Application

To add Views for our Controller class, we need to create a folder inside Views folder with the same name as our Controller and then, add our Views to that folder.

Right-click on the Views folder, and select “New Folder” and name the folder as Employee.

 

To add the View files, right-click on Employee folder inside Views folder and select “New File”. Name it as Index.cshtml. This will create a View file inside Employee folder. Thus, we have created our first View. Similarly, add 4 more Views in Views/Employee folder, Create.cshtml, Delete.cshtml, Details.cshtml, and Edit.cshtml. 

Now, our Views folder will look like this.

 

Since all our Views have been created, we will put codes in View and Controller for performing the CRUD operations.

Index View

This View will be displaying all the employee records present in the database. Additionally, we will also be providing action methods Edit, Details and Delete on each record.

Open Index.cshtml and put the following code in it.
  1. @model IEnumerable<MVCAdoDemo.Models.Employee>    
  2.        
  3. @{    
  4.         ViewData["Title"] = "Index";    
  5.     }    
  6. <h2>Index</h2>    
  7. <p>    
  8.     <a asp-action="Create">Create New</a>    
  9. </p>    
  10. <table class="table">    
  11.     <thead>    
  12.         <tr>    
  13.             <th>    
  14.                 @Html.DisplayNameFor(model => model.Name)    
  15.             </th>    
  16.             <th>    
  17.                 @Html.DisplayNameFor(model => model.Gender)    
  18.             </th>    
  19.             <th>    
  20.                 @Html.DisplayNameFor(model => model.Department)    
  21.             </th>    
  22.             <th>    
  23.                 @Html.DisplayNameFor(model => model.City)    
  24.             </th>    
  25.             <th></th>    
  26.         </tr>    
  27.     </thead>    
  28.     <tbody>    
  29.         @foreach (var item in Model)    
  30. {    
  31.             <tr>    
  32.                 <td>    
  33.                     @Html.DisplayFor(modelItem => item.Name)    
  34.                 </td>    
  35.                 <td>    
  36.                     @Html.DisplayFor(modelItem => item.Gender)    
  37.                 </td>    
  38.                 <td>    
  39.                     @Html.DisplayFor(modelItem => item.Department)    
  40.                 </td>    
  41.                 <td>    
  42.                     @Html.DisplayFor(modelItem => item.City)    
  43.                 </td>    
  44.                 <td>    
  45.                     <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |    
  46.                     <a asp-action="Details" asp-route-id="@item.ID">Details</a> |    
  47.                     <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>    
  48.                 </td>    
  49.             </tr>    
  50.         }    
  51.     </tbody>    
  52. </table>    
Open your EmployeeController.cs file. You can observe that it is empty. Put the following code into it.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using MVCAdoDemo.Models;  
  8.   
  9. namespace MVCAdoDemo.Controllers  
  10. {  
  11.     public class EmployeeController : Controller  
  12.     {  
  13.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  
  14.   
  15.         public IActionResult Index()  
  16.         {  
  17.             List<Employee> lstEmployee = new List<Employee>();  
  18.             lstEmployee = objemployee.GetAllEmployees().ToList();  
  19.   
  20.             return View(lstEmployee);  
  21.         }  
  22.      }  
  23. }  
To handle database operations, we have created an object of EmployeeDataAccessLayer class inside the EmployeeController class.

Create View

This View will be used to add a new employee's data to the database.

Open Create.cshtml and put the following code into it.
  1. @model MVCAdoDemo.Models.Employee    
  2.     
  3. @{    
  4.     ViewData["Title"] = "Create";    
  5. }    
  6. <h2>Create</h2>    
  7. <h4>Employees</h4>    
  8. <hr />    
  9. <div class="row">    
  10.     <div class="col-md-4">    
  11.         <form asp-action="Create">    
  12.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>    
  13.             <div class="form-group">    
  14.                 <label asp-for="Name" class="control-label"></label>    
  15.                 <input asp-for="Name" class="form-control" />    
  16.                 <span asp-validation-for="Name" class="text-danger"></span>    
  17.             </div>    
  18.             <div class="form-group">    
  19.                 <label asp-for="Gender" class="control-label"></label>    
  20.                 <select asp-for="Gender" class="form-control">    
  21.                     <option value="">-- Select Gender --</option>    
  22.                     <option value="Male">Male</option>    
  23.                     <option value="Female">Female</option>    
  24.                 </select>    
  25.                 <span asp-validation-for="Gender" class="text-danger"></span>    
  26.             </div>    
  27.             <div class="form-group">    
  28.                 <label asp-for="Department" class="control-label"></label>    
  29.                 <input asp-for="Department" class="form-control" />    
  30.                 <span asp-validation-for="Department" class="text-danger"></span>    
  31.             </div>    
  32.             <div class="form-group">    
  33.                 <label asp-for="City" class="control-label"></label>    
  34.                 <input asp-for="City" class="form-control" />    
  35.                 <span asp-validation-for="City" class="text-danger"></span>    
  36.             </div>    
  37.             <div class="form-group">    
  38.                 <input type="submit" value="Create" class="btn btn-default" />    
  39.             </div>    
  40.         </form>    
  41.     </div>    
  42. </div>    
  43. <div>    
  44.     <a asp-action="Index">Back to List</a>    
  45. </div>    
  46. @section Scripts {    
  47.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}    
  48. }    

To handle the business logic of Create, open EmployeeController.cs and put the following code into it.

  1. [HttpGet]  
  2. public IActionResult Create()  
  3. {  
  4.     return View();  
  5. }  
  6.   
  7. [HttpPost]  
  8. [ValidateAntiForgeryToken]  
  9. public IActionResult Create([Bind] Employee employee)  
  10. {  
  11.     if (ModelState.IsValid)  
  12.     {  
  13.         objemployee.AddEmployee(employee);  
  14.         return RedirectToAction("Index");  
  15.     }  
  16.     return View(employee);  
  17. }  

The [Bind] attribute is used with parameter “employee” to protect against over-posting. To know more about over-posting, visit here.

Edit View

This View will enable us to edit an existing employee data.

Open Edit.cshtml and put the following code into it.
  1. @model MVCAdoDemo.Models.Employee    
  2.     
  3. @{    
  4.     ViewData["Title"] = "Edit";    
  5. }    
  6. <h2>Edit</h2>    
  7. <h4>Employees</h4>    
  8. <hr />    
  9. <div class="row">    
  10.     <div class="col-md-4">    
  11.         <form asp-action="Edit">    
  12.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>    
  13.             <input type="hidden" asp-for="ID" />    
  14.             <div class="form-group">    
  15.                 <label asp-for="Name" class="control-label"></label>    
  16.                 <input asp-for="Name" class="form-control" />    
  17.                 <span asp-validation-for="Name" class="text-danger"></span>    
  18.             </div>    
  19.             <div class="form-group">    
  20.                 <label asp-for="Gender" class="control-label"></label>    
  21.                 <select asp-for="Gender" class="form-control">    
  22.                     <option value="">-- Select Gender --</option>    
  23.                     <option value="Male">Male</option>    
  24.                     <option value="Female">Female</option>    
  25.                 </select>    
  26.                 <span asp-validation-for="Gender" class="text-danger"></span>    
  27.             </div>    
  28.             <div class="form-group">    
  29.                 <label asp-for="Department" class="control-label"></label>    
  30.                 <input asp-for="Department" class="form-control" />    
  31.                 <span asp-validation-for="Department" class="text-danger"></span>    
  32.             </div>    
  33.             <div class="form-group">    
  34.                 <label asp-for="City" class="control-label"></label>    
  35.                 <input asp-for="City" class="form-control" />    
  36.                 <span asp-validation-for="City" class="text-danger"></span>    
  37.             </div>                
  38.             <div class="form-group">    
  39.                 <input type="submit" value="Save" class="btn btn-default" />    
  40.             </div>    
  41.         </form>    
  42.     </div>    
  43. </div>    
  44. <div>    
  45.     <a asp-action="Index">Back to List</a>    
  46. </div>    
  47. @section Scripts {    
  48.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}    
  49. }    

To handle the business logic of Edit view, open EmployeeController.cs and add the following code to it.

  1. [HttpGet]    
  2. public IActionResult Edit(int? id)    
  3. {    
  4.     if (id == null)    
  5.     {    
  6.         return NotFound();    
  7.     }    
  8.     Employee employee = objemployee.GetEmployeeData(id);    
  9.   
  10.     if (employee == null)    
  11.     {    
  12.         return NotFound();    
  13.     }    
  14.     return View(employee);    
  15. }    
  16.   
  17. [HttpPost]    
  18. [ValidateAntiForgeryToken]    
  19. public IActionResult Edit(int id, [Bind]Employee employee)    
  20. {    
  21.     if (id != employee.ID)    
  22.     {    
  23.         return NotFound();    
  24.     }    
  25.     if (ModelState.IsValid)    
  26.     {    
  27.         objemployee.UpdateEmployee(employee);    
  28.         return RedirectToAction("Index");    
  29.     }    
  30.     return View(employee);    
  31. }     

As you can observe that we have two Edit action methods, one for HttpGet and another for HttpPost.The HttpGet Edit action method will fetch the employee data and populate the fields of Edit view. Once the user clicks on Save button after editing the record, a Post request will be generated which is handled by HttpPost Edit action method.

Details View

This View will display the details of a particular employee. Open Details.cshtml and put the following code into it.
  1. @model MVCAdoDemo.Models.Employee    
  2.     
  3. @{    
  4.     ViewData["Title"] = "Details";    
  5. }    
  6. <h2>Details</h2>    
  7. <div>    
  8.     <h4>Employees</h4>    
  9.     <hr />    
  10.     <dl class="dl-horizontal">    
  11.         <dt>    
  12.             @Html.DisplayNameFor(model => model.Name)    
  13.         </dt>    
  14.         <dd>    
  15.             @Html.DisplayFor(model => model.Name)    
  16.         </dd>    
  17.         <dt>    
  18.             @Html.DisplayNameFor(model => model.Gender)    
  19.         </dt>    
  20.         <dd>    
  21.             @Html.DisplayFor(model => model.Gender)    
  22.         </dd>    
  23.         <dt>    
  24.             @Html.DisplayNameFor(model => model.Department)    
  25.         </dt>    
  26.         <dd>    
  27.             @Html.DisplayFor(model => model.Department)    
  28.         </dd>    
  29.         <dt>    
  30.             @Html.DisplayNameFor(model => model.City)    
  31.         </dt>    
  32.         <dd>    
  33.             @Html.DisplayFor(model => model.City)    
  34.         </dd>    
  35.     </dl>    
  36. </div>    
  37. <div>    
  38.     <a asp-action="Edit" asp-route-id="@Model.ID">Edit</a> |    
  39.     <a asp-action="Index">Back to List</a>    
  40. </div>    

To handle the business logic of Details view,open EmployeeController.cs and add the following code to it.

  1. [HttpGet]  
  2. public IActionResult Details(int? id)  
  3. {  
  4.     if (id == null)  
  5.     {  
  6.         return NotFound();  
  7.     }  
  8.     Employee employee = objemployee.GetEmployeeData(id);  
  9.   
  10.     if (employee == null)  
  11.     {  
  12.         return NotFound();  
  13.     }  
  14.     return View(employee);  
  15. }   

Delete View

This View will help us to remove the employee data.

Open Delete.cshtml and put the following code into it.
  1. @model MVCAdoDemo.Models.Employee    
  2.     
  3. @{    
  4.     ViewData["Title"] = "Delete";    
  5. }    
  6. <h2>Delete</h2>    
  7. <h3>Are you sure you want to delete this?</h3>    
  8. <div>    
  9.     <h4>Employees</h4>    
  10.     <hr />    
  11.     <dl class="dl-horizontal">    
  12.         <dt>    
  13.             @Html.DisplayNameFor(model => model.Name)    
  14.         </dt>    
  15.         <dd>    
  16.             @Html.DisplayFor(model => model.Name)    
  17.         </dd>    
  18.         <dt>    
  19.             @Html.DisplayNameFor(model => model.Gender)    
  20.         </dt>    
  21.         <dd>    
  22.             @Html.DisplayFor(model => model.Gender)    
  23.         </dd>    
  24.         <dt>    
  25.             @Html.DisplayNameFor(model => model.Department)    
  26.         </dt>    
  27.         <dd>    
  28.             @Html.DisplayFor(model => model.Department)    
  29.         </dd>    
  30.         <dt>    
  31.             @Html.DisplayNameFor(model => model.City)    
  32.         </dt>    
  33.         <dd>    
  34.             @Html.DisplayFor(model => model.City)    
  35.         </dd>    
  36.     </dl>    
  37.     
  38.     <form asp-action="Delete">    
  39.         <input type="hidden" asp-for="ID" />    
  40.         <input type="submit" value="Delete" class="btn btn-default" /> |    
  41.         <a asp-action="Index">Back to List</a>    
  42.     </form>    
  43. </div>    

To handle the business logic of Delete view, open EmployeeController.cs and add the following code to it.

  1. [HttpGet]  
  2. public IActionResult Delete(int? id)  
  3. {  
  4.     if (id == null)  
  5.     {  
  6.         return NotFound();  
  7.     }  
  8.     Employee employee = objemployee.GetEmployeeData(id);  
  9.   
  10.     if (employee == null)  
  11.     {  
  12.         return NotFound();  
  13.     }  
  14.     return View(employee);  
  15. }  
  16.   
  17. [HttpPost, ActionName("Delete")]  
  18. [ValidateAntiForgeryToken]  
  19. public IActionResult DeleteConfirmed(int? id)  
  20. {  
  21.     objemployee.DeleteEmployee(id);  
  22.     return RedirectToAction("Index");  
  23. }  

To complete the Delete operation, we need two Delete methods accepting same parameter (Employee Id). But two methods with the same name and method signature will create a compile-time error and if we rename the Delete method, then routing won't be able to find it as ASP.NET maps URL segments to action methods by name. So, to resolve this issue, we put ActionName("Delete") attribute to the DeleteConfirmed method. This attribute performs mapping for the routing system so that a URL that includes /Delete/ for a POST request will find the DeleteConfirmed method.

When we click on Delete link on the Index page, it will send a Get request and return a View of the employee using HttpGet Delete method. When we click on Delete button on this View, it will send a Post request to delete the record which is handled by the HttpPost DeleteConfirmed method. Performing a delete operation in response to a Get request (or for that matter, performing an edit operation, create operation, or any other operation that changes data) opens up a security hole. Hence, we have two separate methods.

Before launching the application, we will configure route URLs. Open Startup.cs file to set the format for routing. Scroll down to the app.UseMvc method, where you can set the route URL.

Make sure that your route url is set like this

  1. app.UseMvc(routes =>  
  2.  {  
  3.      routes.MapRoute(  
  4.          name: "default",  
  5.          template: "{controller=Home}/{action=Index}/{id?}");  
  6.  });  
This URL pattern sets HomeController as default controller and Index method as default action method, whereas Id parameter is optional. Default and optional route parameters need not be present in the URL path for a match. If we do not append any controller name in the URL then it will take HomeController as default controller and Index method of HomeController as default action method. Similarly, if we append only Controller name in the URL, it will navigate to Index action method of that controller.

Now, press F5 to launch the application and navigate to Employee controller by appending /Employee in the URL.

You can see the page as shown below.
 


Click on CreateNew to navigate to the Create view. Add a new Employee record as shown in the image below.
 
If we miss the data in any field while creating the employee record, we will get a required field validation error message.
 
After inserting the data into all the fields, click on "Create" button. The new employee record will be created and you will be redirected to the Index view, displaying records of all the employees. Here, we can also see action methods Edit, Details, and Delete.


If we want to edit an existing employee record, then click Edit action link. It will open Edit View as below where we can change the employee data.
 
Here, we have changed the City of employee Dhiraj from Mumbai to New Delhi. Click on "Save" to return to the Index view to see the updated changes as highlighted in the image below.


If we miss any fields while editing employee records, then Edit view will also throw a required field validation error message.
If you want to see the details of any Employee, then click on Details action link, which will open the Details view, as shown in the image below.


Click on "Back to List" to go back to Index View. Now, we will perform the Delete operation on an employee named Rahul. Click on Delete action link which will open Delete view asking for a confirmation to delete.
 
Once we click on Delete button, it will send HttpPost request to delete employee record and we will be redirected to the Index view. Here, we can see that the employee with name Rahul has been removed from our record.
 
Conclusion

We have learned about creating a sample MVC web application using ASP.Net Core 2.0, ADO.NET and SQL server with the help of Visual Studio Code. Please refer to the attached code for better understanding. Please provide your valuable feedback in the comments section. 

Next Recommended Readings