Introduction
In this article, I am going to show you how to perform Create, Read, Update, Delete (also called the CRUD) operations in ASP.NET Core 2.1 MVC application using class library project with ADO.NET. We will be creating a sample Customer record in order to perform the CRUD operation in ASP.NET Core 2.1 MVC application using stored procedure and ADO.NET but I am not using Models. I have used 2 class library projects for CRUD operation.
We will be using Visual Studio 2017 (version 15.9.13 or above) and SQL Server 2017 or you can use SQL Server 2008 or above.
What is a Class Library?
A Class Library project is used for code reusability. Code reusability is one of the key features of modern programming languages. It helps to reduce errors, code duplication, and development time.
Here, I have created 2 class library projects. The first class library project contains all class entities/properties and the second class library project contains all CRUD operation methods. All these properties and methods are consumed in ASP.NET 2.1 MVC Application for CURD operations.
Prerequisites
- Install Visual Studio 2017 Updated version 15.9.13
- Install .Net Core SDK 2.1 or above
- SQL Server 2017
Now, we will create our ASP.NET Core 2.1 MVC Application. First of all, we will create a database, a table, and a stored procedure.
Creating Database, Table, and Stored Procedures
Step 1 - To create a Database
Open your SQL Server and use the following script to create the “CoreMvcDB” Database.
Create database CoreMvcDB
Step 2 - Create a Table
Open your SQL Server and use the following script to create “tbl_Customer” table.
- create Table tbl_Customer(
- CustomerId int IDENTITY(1,1) NOT NULL primary key,
- Name Varchar(20) NOT NULL,
- Address varchar(100) not null,
- City Varchar(20) NOT NULL,
- Country Varchar(20) NOT NULL,
- Gender Varchar(6) NOT NULL ,
- MobileNo varchar(15) NOT NULL,
- MailId varchar(20) NOT NULL
- )
Now we will be creating a stored procedure for add, delete, update, and get Customer data.
Step 3 - To create a stored procedure
Now we will create a stored procedure to insert a Customer Record to the Database.
Open your SQL Server and use the following script to create a procedure
To insert a CustomerRecord
- Create procedure sp_AddCustomer
- (
- @Name VARCHAR(20),
- @Address varchar(100),
- @City VARCHAR(20),
- @Country VARCHAR(20),
- @Gender VARCHAR(6),
- @MobileNo varchar(15),
- @MailId varchar(20)
- )
- As
- Begin
- Insert into tbl_Customer (Name,Address,City,Country, Gender,MobileNo,MailId)
- Values (@Name,@Address,@City,@Country, @Gender,@MobileNo,@MailId)
- End
To Update a CustomerRecord
- Create procedure sp_UpdateCustomer
- (
- @CustomerId INTEGER ,
- @Name VARCHAR(20),
- @Address varchar(100),
- @City VARCHAR(20),
- @Country VARCHAR(20),
- @Gender VARCHAR(6),
- @MobileNo varchar(15),
- @MailId varchar(20)
- )
- As
- begin
- Update tbl_Customer
- set Name=@Name,
- Address=@Address,
- City=@City,
- Country=@Country,
- Gender=@Gender,
- MobileNo=@MobileNo,
- MailId= @MailId
-
- where CustomerId=@CustomerId
- End
To Delete a CustomerRecord
- Create procedure sp_DeleteCustomer
- (
- @CustomerId int
- )
- As
- begin
- Delete from tbl_Customer where CustomerId=@CustomerId
- End
To Get a Single CustomerRecord
- Create procedure sp_GetCustomerByID
- (
- @CustomerId int
- )
- As
- Begin
- SELECT * FROM tbl_Customer WHERE CustomerID= @CustomerId
- End
To View All CustomerRecords
- Create procedure sp_GetAllCustomers
- As
- Begin
- select
- CustomerId,
- Name,
- Address,
- City,
- Country,
- Gender,
- MobileNo,
- MailId
- from tbl_Customer
- End
Now, our database part is completed. So now we will create our Asp.Net core MVC application.
Step 1- Create an ASP.NET Core 2.1 MVC Project
Open Visual Studio and select File -> New -> Project.
After selecting the project, a "New Project" dialog will open. Then you can select .NET Core inside the Visual C# menu from the left side panel.
Then, select “ASP.NET Core web application“from available project types. Give a name to the project as “CoreCurdMVC_Classlibrary” and press OK. Here my project name is “CoreCurdMVC_Classlibrary”.
After clicking on the OK button, a new dialog box will open and you can select the project template. You can see two drop-down menus at the top left of the template window. Then, you can select “.NET Core” and “ASP.NET Core 2.1” from these dropdowns list. Then Select “Web application (Model-View-Controller)” template and press OK to create Asp.Net Core MVC project and select the tick mark for configure for HTTPS.
Step 2 - Add a class library project
Right click on the solution folder and select Add -> New Project menu option and you can select .NET Core in the left side and select Class Library (.NET Core) project template in the right side and I give my project name “Customer_Entities”.
Now, add a new class on Customer_Entities project and Name it as “Customer.cs”.
This class will contain our Customer entities/ properties.
Now open Customer.cs class and put the following code in it. We are also adding the required validators to the fields of Customer class, so we need to use System.ComponentModel.DataAnnotations at the top.
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.ComponentModel.DataAnnotations;
-
- namespace Customer_Entities
- {
- public class Customer
- {
- public int ID { get; set; }
- [Required(ErrorMessage = "Enter Your Name")]
- [StringLength(15, ErrorMessage = "Name should be less than or equal to Fifteen characters.")]
- public string Name { get; set; }
- [Required(ErrorMessage = "Enter Your Address")]
- [StringLength(50, ErrorMessage = "Address should be less than or equal to fifty characters.")]
- public string Address { get; set; }
- [Required(ErrorMessage = "Enter Your Gender")]
- public string Gender { get; set; }
- [Required(ErrorMessage = "Enter Your City")]
- [StringLength(10, ErrorMessage = "City should be less than or equal to ten characters.")]
- public string City { get; set; }
- [Required(ErrorMessage = "Enter Your Country")]
- [StringLength(10, ErrorMessage = "Country should be less than or equal to ten characters.")]
- public string Country { get; set; }
- [Required(ErrorMessage = "You must provide a Mobile Number")]
- [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Mobile number")]
- public string Mobile { get; set; }
- [Required(ErrorMessage = "Enter Your Mail ID")]
- [RegularExpression(@"^[\w-\._\+%]+@(?:[\w-]+\.)+[\w]{2,6}$", ErrorMessage = "Please enter a valid email address")]
- public string Email { get; set; }
- }
- }
In the above code, I have used some attributes to check validation of controls, which are based on control values. For textbox name, Address, City and Country Validation, I have put [Required(ErrorMessage = "Enter Your Name")].
This code will be executed if your input value is empty in controls. Now, if the user puts something in but this does not satisfy the standard validation, then it will show error as given below.
[StringLength(15, ErrorMessage = "Name should be less than or equal to Fifteen characters.")]
The user puts only 15 characters to control input values. Like this, you can check for others.
In Mobile, I can enter only 10 digit valid mobile no.
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Mobile number")]
In Email, you can enter only a valid Email Id with @ symbol.
[RegularExpression(@"^[\w-\._\+%]+@(?:[\w-]+\.)+[\w]{2,6}$", ErrorMessage = "Please enter a valid email address")]
Step 3 - Add another class library project
Right click on the solution and select Add -> New Project menu option. On the New Project dialog, select .NET Core in the left side and Class Library (.NET Core) template in the right side and I give my project name “Customer_database”.
Now add a new class on “Customer_database” project and Name it as “CustomerDataAccess_Layer.cs”.
This class will contain our database related operations.
Now, the project structure is given below.
Open CustomerDataAccess_Layer.cs and put the following code to handle the database operations.
Before that add a reference to the class library project to access the functionality. Add reference “Customer_Entities” project in “Customer_database” project.
Make sure to put your connection string.
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- using Customer_Entities;
-
- namespace Customer_database
- {
- public class CustomerDataAccess_Layer
- {
- string connectionString = "put your connection string here";
-
- public IEnumerable<Customer> GetAllCustomers()
- {
- List<Customer> lstCustomer = new List<Customer>();
-
- using (SqlConnection con = new SqlConnection(connectionString))
- {
- SqlCommand cmd = new SqlCommand("sp_GetAllCustomers", con);
- cmd.CommandType = CommandType.StoredProcedure;
-
- con.Open();
- SqlDataReader sdr = cmd.ExecuteReader();
-
- while (sdr.Read())
- {
- Customer Customer = new Customer();
-
- Customer.ID = Convert.ToInt32(sdr["CustomerID"]);
- Customer.Name = sdr["Name"].ToString();
- Customer.Address = sdr["Address"].ToString();
- Customer.Gender = sdr["Gender"].ToString();
- Customer.Country = sdr["Country"].ToString();
- Customer.City = sdr["City"].ToString();
- Customer.Mobile = sdr["MobileNo"].ToString();
- Customer.Email = sdr["MailId"].ToString();
- lstCustomer.Add(Customer);
- }
- con.Close();
- }
- return lstCustomer;
- }
-
-
- public void AddCustomer(Customer Customer)
- {
- using (SqlConnection con = new SqlConnection(connectionString))
- {
- SqlCommand cmd = new SqlCommand("sp_AddCustomer", con);
- cmd.CommandType = CommandType.StoredProcedure;
-
- cmd.Parameters.AddWithValue("@Name", Customer.Name);
- cmd.Parameters.AddWithValue("@Address", Customer.Address);
- cmd.Parameters.AddWithValue("@Gender", Customer.Gender);
- cmd.Parameters.AddWithValue("@Country", Customer.Country);
- cmd.Parameters.AddWithValue("@City", Customer.City);
- cmd.Parameters.AddWithValue("@MobileNo", Customer.Mobile);
- cmd.Parameters.AddWithValue("@MailId", Customer.Email);
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
- }
-
-
- public void UpdateCustomer(Customer Customer)
- {
- using (SqlConnection con = new SqlConnection(connectionString))
- {
- SqlCommand cmd = new SqlCommand("sp_UpdateCustomer", con);
- cmd.CommandType = CommandType.StoredProcedure;
-
- cmd.Parameters.AddWithValue("@CustomerId", Customer.ID);
- cmd.Parameters.AddWithValue("@Name", Customer.Name);
- cmd.Parameters.AddWithValue("@Address", Customer.Address);
- cmd.Parameters.AddWithValue("@Gender", Customer.Gender);
- cmd.Parameters.AddWithValue("@Country", Customer.Country);
- cmd.Parameters.AddWithValue("@City", Customer.City);
- cmd.Parameters.AddWithValue("@MobileNo", Customer.Mobile);
- cmd.Parameters.AddWithValue("@MailId", Customer.Email);
-
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
- }
-
-
- public Customer GetCustomerData(int? id)
- {
- Customer Customer = new Customer();
-
- using (SqlConnection con = new SqlConnection(connectionString))
- {
-
- SqlCommand cmd = new SqlCommand("sp_GetCustomerByID", con);
- cmd.CommandType = CommandType.StoredProcedure;
-
- cmd.Parameters.AddWithValue("@CustomerId", id);
- con.Open();
- SqlDataReader sdr = cmd.ExecuteReader();
-
- while (sdr.Read())
- {
- Customer.ID = Convert.ToInt32(sdr["CustomerID"]);
- Customer.Name = sdr["Name"].ToString();
- Customer.Address = sdr["Address"].ToString();
- Customer.Gender = sdr["Gender"].ToString();
- Customer.Country = sdr["Country"].ToString();
- Customer.City = sdr["City"].ToString();
- Customer.Mobile = sdr["MobileNo"].ToString();
- Customer.Email = sdr["MailId"].ToString();
- }
- }
- return Customer;
- }
-
-
- public void DeleteCustomer(int? id)
- {
-
- using (SqlConnection con = new SqlConnection(connectionString))
- {
- SqlCommand cmd = new SqlCommand("sp_DeleteCustomer", con);
- cmd.CommandType = CommandType.StoredProcedure;
-
- cmd.Parameters.AddWithValue("@CustomerId", id);
-
- con.Open();
- cmd.ExecuteNonQuery();
- con.Close();
- }
- }
- }
- }
Step 4 - Adding the new controller to the application
Right click on Controllers folder and Select add New Item.
An “Add New Item” dialog box will open and you can Select Asp.Net Core from the left panel, then select “Controller Class” from templates panel and put the name as CustomerController.cs. then Press OK.
Now our CustomerController has been created. We will put our business logic in this controller.
Step 5 - 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 name and then add our views to that folder.
Right-click on the Views folder, and then Add >> New Folder and name the folder as Customer.
Now Right click on the Views/Customer folder, and then select Add >> New Item.
An “Add New Item” dialog box will open and you can Select Asp.Net CORE from the left panel, then select “Razor View Page” from templates panel, and put the view name as Index.cshtml. Then Press OK.
Similarly add 4 more views in Views/Customer folder, Create_customer.cshtml, Delete_customer.cshtml, customer_Details.cshtml, and Edit_customer.cshtml.
Now, our Views folder will look like this,
Let us put our codes in views and controller to perform the CRUD operation.
Create View
This view is used for Adding a new Customer data to the database.
Open Create_customer.cshtml and put following code into it.
- @model Customer_Entities.Customer
- @{
- ViewData["Title"] = "Create";
- }
- <h2>Create Customers </h2>
- <hr />
- <div class="row">
- <div class="col-md-4">
- <form asp-action="Create_customer">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <div class="form-group">
- <label asp-for="Name" class="control-label"></label>
- <input asp-for="Name" class="form-control" />
- <span asp-validation-for="Name" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Address" class="control-label"></label>
- <input asp-for="Address" class="form-control" />
- <span asp-validation-for="Address" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="City" class="control-label"></label>
- <input asp-for="City" class="form-control" />
- <span asp-validation-for="City" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Country" class="control-label"></label>
- <input asp-for="Country" class="form-control" />
- <span asp-validation-for="Country" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Gender" class="control-label"></label>
- <select asp-for="Gender" class="form-control">
- <option value="">-- Select Gender --</option>
- <option value="Male">Male</option>
- <option value="Female">Female</option>
- </select>
- <span asp-validation-for="Gender" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Mobile" class="control-label"></label>
- <input asp-for="Mobile" class="form-control" />
- <span asp-validation-for="Mobile" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Email" class="control-label"></label>
- <input asp-for="Email" class="form-control" />
- <span asp-validation-for="Email" class="text-danger"></span>
- </div>
- <div class="form-group">
- <input type="submit" value="Create" class="btn btn-primary" />
- </div>
- </form>
- </div>
- </div>
- <div>
- <a asp-action="Index">Back to List</a>
- </div>
- @section Scripts {
- @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
- }
To handle database operations, first we will create an object of CustomerDataAccess_Layer class inside the CustomerController class.
Before that add a reference to the class library project to access the functionality. Add reference “Customer_Entities” project in “CoreCurdMVC_Classlibrary” project.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using CoreCurdMVC_Classlibrary;
- using Customer_Entities;
- using Customer_database;
-
-
- namespace CoreCurdMVC_Classlibrary.Controllers
- {
- public class CustomerController : Controller
- {
- CustomerDataAccess_Layer objCustomer = new CustomerDataAccess_Layer();
Open CustomerController.cs and put following code into it to maintain the business logic of Create_customer.cshtml view.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using CoreCurdMVC_Classlibrary;
- using Customer_Entities;
- using Customer_database;
-
-
- namespace CoreCurdMVC_Classlibrary.Controllers
- {
- public class CustomerController : Controller
- {
- CustomerDataAccess_Layer objCustomer = new CustomerDataAccess_Layer();
-
- [HttpGet]
- public IActionResult Create_customer()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public IActionResult Create_customer([Bind] Customer cust)
- {
- if (ModelState.IsValid)
- {
- objCustomer.AddCustomer(cust);
- return RedirectToAction("Index");
- }
- return View(objCustomer);
- }
The [Bind] attribute is used with parameter “cust” to protect against over-posting.
Index View
This view is displaying all the Customer records available in the database. Also, all the operation, Edit, Details and Delete on each record can be done form this (Index.cshtml) view.
Open Index.cshtml and puts the following codes.
- @model IEnumerable<Customer_Entities.Customer>
-
- @{
- ViewData["Title"] = "Index";
- }
- <h2>Index</h2>
- <p>
- <a asp-action="Create_customer">Create New</a>
- </p>
- <table class="table table-bordered table-responsive">
- <thead>
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Address)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.City)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Country)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Gender)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Mobile)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Email)
- </th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var item in Model)
- {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Address)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.City)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Country)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Gender)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Mobile)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Email)
- </td>
- <td>
- <a asp-action="Edit_customer" asp-route-id="@item.ID">Edit</a> |
- <a asp-action="customer_Details" asp-route-id="@item.ID">Details</a> |
- <a asp-action="Delete_customer" asp-route-id="@item.ID">Delete</a>
- </td>
- </tr>
- }
- </tbody>
- </table>
Open CustomerController.cs and add following code in Index method to maintain the business logic of Index view.
- public IActionResult Index()
- {
- List<Customer> customers = new List<Customer>();
- customers = objCustomer.GetAllCustomers().ToList();
- return View(customers);
- }
Edit View
This view is used to edit an existing Customer data.
Open Edit_customer.cshtml and put the following code into it.
- @model Customer_Entities.Customer
-
- @{
- ViewData["Title"] = "Edit";
- }
- <h2>Edit Customer </h2>
- <hr />
- <div class="row">
- <div class="col-md-4">
- <form asp-action="Edit_customer">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <input type="hidden" asp-for="ID" />
- <div class="form-group">
- <label asp-for="Name" class="control-label"></label>
- <input asp-for="Name" class="form-control" />
- <span asp-validation-for="Name" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Address" class="control-label"></label>
- <input asp-for="Address" class="form-control" />
- <span asp-validation-for="Address" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Gender" class="control-label"></label>
- <select asp-for="Gender" class="form-control">
- <option value="">-- Select Gender --</option>
- <option value="Male">Male</option>
- <option value="Female">Female</option>
- </select>
- <span asp-validation-for="Gender" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Country" class="control-label"></label>
- <input asp-for="Country" class="form-control" />
- <span asp-validation-for="Country" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="City" class="control-label"></label>
- <input asp-for="City" class="form-control" />
- <span asp-validation-for="City" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Mobile" class="control-label"></label>
- <input asp-for="Mobile" class="form-control" />
- <span asp-validation-for="Mobile" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Email" class="control-label"></label>
- <input asp-for="Email" class="form-control" />
- <span asp-validation-for="Email" class="text-danger"></span>
- </div>
- <div class="form-group">
- <input type="submit" value="Save" class="btn btn-primary" />
- </div>
- </form>
- </div>
- </div>
- <div>
- <a asp-action="Index">Back to List</a>
- </div>
- @section Scripts {
- @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
- }
Open CustomerController.cs and add following code to it to maintain the business logic of Edit_customer.cshtml view.
- public IActionResult Edit_customer(int? id)
- {
- if (id == null)
- {
- return NotFound();
- }
- Customer customer = objCustomer.GetCustomerData(id);
-
- if (customer == null)
- {
- return NotFound();
- }
- return View(customer);
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public IActionResult Edit_customer(int id, [Bind] Customer cust)
- {
- if (id != cust.ID)
- {
- return NotFound();
- }
- if (ModelState.IsValid)
- {
- objCustomer.UpdateCustomer(cust);
- return RedirectToAction("Index");
- }
- return View(objCustomer);
- }
You can see that we have two Edit_customer action methods, the first one is for HttpGet method and the second one is for HttpPost method. The HttpGet Edit_customer action method will retrive the Custoemer data and fills the fields to edit view. After the user clicks Save by editing the record, a Post request will be created which is handled by HttpPost Edit_customer action method.
Details View
This view is used to display the details of a particular Customer. Add following codes on customer_Details .cshtml.
- @model Customer_Entities.Customer
-
- @{
- ViewData["Title"] = "Details";
- }
- <h2> Customer Details</h2>
- <div>
- <hr />
- <dl class="dl-horizontal">
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Address)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Address)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.City)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.City)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Country)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Country)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Mobile)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Mobile)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Email)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Email)
- </dd>
- </dl>
- </div>
- <div>
- <a asp-action="Edit_customer" asp-route-id="@Model.ID">Edit</a> |
- <a asp-action="Index">Back to List</a>
- </div>
Open CustoemrController.cs and add the following code to it to maintain the business logic of Details View(customer_Details.cshtml).
- [HttpGet]
- public IActionResult customer_Details(int? id)
- {
- if (id == null)
- {
- return NotFound();
- }
- Customer objcustomer = objCustomer.GetCustomerData(id);
-
- if (objcustomer == null)
- {
- return NotFound();
- }
- return View(objcustomer);
- }
Delete View
This view is used to remove a particular Custoemr data. Open Delete_customer.cshtml and put following code into it.
- @model Customer_Entities.Customer
-
- @{
- ViewData["Title"] = "Delete";
- }
- <h2>Delete</h2>
- <h3>Are you sure you want to delete this?</h3>
- <div>
- <h4>Customer</h4>
- <hr />
- <dl class="dl-horizontal">
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Address)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Address)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.City)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.City)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Country)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Country)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Mobile)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Mobile)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Email)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Email)
- </dd>
- </dl>
-
- <form asp-action="Delete_customer">
- <input type="hidden" asp-for="ID" />
- <input type="submit" value="Delete" class="btn btn-primary" /> |
- <a asp-action="Index">Back to List</a>
- </form>
- </div>
Open CustomerController.cs and add following code to it to maintain the business logic of Delete_customer.cshtml view.
- [HttpGet]
- public IActionResult Delete_customer(int? id)
- {
- if (id == null)
- {
- return NotFound();
- }
- Customer objcustomer = objCustomer.GetCustomerData(id);
-
- if (objcustomer == null)
- {
- return NotFound();
- }
- return View(objcustomer);
- }
-
- [HttpPost, ActionName("Delete_customer")]
- [ValidateAntiForgeryToken]
- public IActionResult DeleteConfirmed(int? id)
- {
- objCustomer.DeleteCustomer(id);
- return RedirectToAction("Index");
- }
In Delete operation we need two Delete methods with the same parameter (Customer Id). But both the methods havethe same name and the same method signature can create a compile time error, if we rename the Delete method then routing will not able to map the URL segments to action methods by its name. So, to resolve this issue we can use ActionName() attributes, it is used for changing the action method name, so we put ActionName("Delete_customer") attribute to the DeleteConfirmed method. That attribute performs mapping for the routing system so that a URL includes /Delete_customer/ for a POST request to find the DeleteConfirmed action method.
When you click the Delete link on the Index page, it will send a Get request and return a View of the Customer using HttpGet Delete_customer method. When you click Delete on this view, it will send a Post request to delete the record which is handled by the HttpPost DeleteConfirmed method.
Step 5 - Add a new menu
Edit the Views/Shared/_Layout page and add a new menu as “AddCustomer”. For that, add the below code.
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
- <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
- <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
-
- <li><a asp-area="" asp-controller="Customer" asp-action="Index">ADDCustomer</a></li>
- </ul>
- </div>
Step 6
Now press F5 to launch the application or Run the application and you can see the output page as shown below.
Click on AddCustomer menu navigate to Index view. It will show all available customer records already saved in data base. Below is the list of records.
Click Create New to navigate Create view. Then you can Add a new Customer record as shown in the image below.
If you have missed any field while creating a Customer Record, you will see the required field validation error message.
After inserting the data in all the fields, then you click the "Create" button. The new Customer record will be created and it will be redirected to the Index view and display records of all the Customers. Also, we can see action methods Like Edit, Details, and Delete.
If you want to edit an existing customer record, then click Edit action link. It will open Edit View where you can change the Customer data.
If you miss any fields while editing Customer records, then Edit view will also throw the required field validation error message.
If you want to see the details of any Customer, then click the Details action link, it will open the Customer Details view, as shown in the image below.
If you click "Back to List", it will redirect Index view. Now, we will perform Delete operation on a customer named Chittaranjan. Click Delete action link which will open Delete view asking for a confirmation to delete.
Once you click the Delete button, it will send HttpPost request to delete Customer record and it will be redirected to the Index view. Here, we can see that the Customer with name the Chittaranjan has been deleted from our records.
Conclusion
You have learned how to create a sample ASP.NET Core 2.1 MVC application using Class library project and ADO.NET with the help of Visual Studio 2017. I have used stored procedures to handle CRUD operations at the database level. Post your valuable feedback in the comments section.