Updated March 15, 2023
Introduction to ASP.NET MVC Example
ASP.NET MVC is the Controllable Web Application that depicts the MVC pattern called the Model-View-Controller. It describes the separation of Code or concerns like View is for UI, Controller to handle the requests, and Models for the logical design. ASP.NET MVC is an Open Source Software. In this article we will learn in detail about ASP.NET MVC Example.
ASP.NET MVC Example
Let’s create an MVC Application. To start step by step method from the creation of the MVC Application,
To select FileàNewà Project, choose ASP.NET Web Application template, give the proper name to the project, and click OK.
Choose the Empty template in this dialog, set View Engine as Razor, and Click OK.
Once given all the Project Solutions looks like as shown below folder structure,
Then, add the new class in the Model folder and create a new model class and name it as EmployeeClassModel.cs, as shown below,
EmployeeClassModel.cs
public class EmployeeClassModel
{
[Display(Name = "Id")]
public int Empid { get; set; }
[Required(ErrorMessage = " First name is Required ")]
public string Name { get; set; }
[Required(ErrorMessage = " City Name is Required ")]
public string City { get; set; }
[Required(ErrorMessage = "Address is Required ")]
public string Address { get; set; }
}
Then add the Controller by clicking Addà Newà Controller and giving the suitable name to it,
Create the Table Employee table
CREATE TABLE [dbo].[Employee]
(
[Id] INT NOT NULL PRIMARY KEY,
Name varchar(50) null,
City varchar(50) null,
Address varchar(50)
)
Stored Procedures as follows,
Create procedure [dbo].[AddNewEmpDetails]
(
@Name varchar (50),
@City varchar (50),
@Address varchar (50)
)
as
begin
Insert into Employee values(@Name,@City,@Address)
End
go
Create Procedure [dbo].[GetEmployees]
as
begin
select *from Employee
End
go
Create procedure [dbo].[UpdateEmpDetails]
(
@EmpId int,
@Name varchar (50),
@City varchar (50),
@Address varchar (50)
)
as
begin
Update Employee
set Name=@Name,
City=@City,
Address=@Address
where Id=@EmpId
End
go
Create procedure [dbo].[DeleteEmpById]
(
@EmpId int
)
as
begin
Delete from Employee where Id=@EmpId
End
To create the new Repository Folder, create the method called EmpRepository.cs for doing the CRUD Operations.
EmpRepository.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Mvc_CRUD_DB_SP.Models;
namespace Mvc_CRUD_DB_SP.Repository
{
public class EmpRepository
{
private SqlConnection con;
//Connection_String
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["db_conn"].ToString();
con = new SqlConnection(constr);
}
//adding emp_details
public bool AddEmployee(EmployeeClassModel obj)
{
connection();
SqlCommand com = new SqlCommand("AddNewEmpDetails", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Name", obj.Name);
com.Parameters.AddWithValue("@City", obj.City);
com.Parameters.AddWithValue("@Address", obj.Address);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
//displaying emp_details in list
public List<EmployeeClassModel> GetAllEmployees()
{
connection();
List<EmployeeClassModel> EmpList = new List<EmployeeClassModel>();
SqlCommand com = new SqlCommand("GetEmployees", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();
//binding list items
EmpList = (from DataRow dr in dt.Rows
select new EmployeeClassModel()
{
Empid = Convert.ToInt32(dr["Id"]),
Name = Convert.ToString(dr["Name"]),
City = Convert.ToString(dr["City"]),
Address = Convert.ToString(dr["Address"])
}).ToList();
return EmpList;
}
//updating emp_details
public bool UpdateEmployee(EmployeeClassModel obj)
{
connection();
SqlCommand com = new SqlCommand("UpdateEmpDetails", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@EmpId", obj.Empid);
com.Parameters.AddWithValue("@Name", obj.Name);
com.Parameters.AddWithValue("@City", obj.City);
com.Parameters.AddWithValue("@Address", obj.Address);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
//deleting emp_details
public bool DeleteEmployee(int Id)
{
connection();
SqlCommand com = new SqlCommand("DeleteEmpById", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@EmpId", Id);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
}
}
EmployeeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc_CRUD_DB_SP.Models;
using Mvc_CRUD_DB_SP.Repository;
namespace Mvc_CRUD_DB_SP.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee/GetAllEmpDetails
public ActionResult GetAllEmpDetails()
{
EmpRepository EmpRepo = new EmpRepository();
ModelState.Clear();
return View(EmpRepo.GetAllEmployees());
}
// GET: Employee/AddEmployee
public ActionResult AddEmployee()
{
return View();
}
// POST: Employee/AddEmployee
[HttpPost]
public ActionResult AddEmployee(EmployeeClassModel Emp)
{
try
{
if (ModelState.IsValid)
{
EmpRepository EmpRepo = new EmpRepository();
if (EmpRepo.AddEmployee(Emp))
{
ViewBag.Message = "Employee details added successfully";
}
}
return View();
}
catch
{
return View();
}
}
// GET: Employee/EditEmpDetails/5
public ActionResult EditEmpDetails(int id)
{
EmpRepository EmpRepo = new EmpRepository();
return View(EmpRepo.GetAllEmployees().Find(Emp => Emp.Empid == id));
}
// POST: Employee/EditEmpDetails/5
[HttpPost]
public ActionResult EditEmpDetails(int id, EmployeeClassModel obj)
{
try
{
EmpRepository EmpRepo = new EmpRepository();
EmpRepo.UpdateEmployee(obj);
return RedirectToAction("GetAllEmpDetails");
}
catch
{
return View();
}
}
// GET: Employee/DeleteEmp/5
public ActionResult DeleteEmp(int id)
{
try
{
EmpRepository EmpRepo = new EmpRepository();
if (EmpRepo.DeleteEmployee(id))
{
ViewBag.AlertMsg = "Employee details deleted successfully";
}
return RedirectToAction("GetAllEmpDetails");
}
catch
{
return View();
}
}
}
}
Once creating all the major coding methods, then create the Views,
AddEmployee.cshtml
@model Mvc_CRUD_DB_SP.Models.EmployeeClassModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Add Employee</h4>
<div>
@Html.ActionLink("Back to Employee List", "GetAllEmpDetails")
</div>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10" style="color:green">
@ViewBag.Message
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
GetAllEmpDetails.cshtml
@model IEnumerable<Mvc_CRUD_DB_SP.Models.EmployeeClassModel>
<p>
@Html.ActionLink("Add New Employee", "AddEmployee")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
@Html.HiddenFor(model => item.Empid)
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.ActionLink("Edit", "EditEmpDetails", new { id = item.Empid }) |
@Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid }, new { onclick = "return confirm('Are sure wants to delete?');" })
</td>
</tr>
}
</table>
Likewise, do for the updated model the same procedure to create in EditEmpDetails to view and update/edit the details of employees.
The RouteConfig.cs file will be as coded below, which denotes that the default action method will be AddEmployee it implies once the application executes, the AddEmployee View will be executed initially,
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 = "Employee", action = "AddEmployee", id = UrlParameter.Optional }
);
}
}
Output
Conclusion
In this article, I have explained the sample application of ASP.NET MVC, which consists of three Folders of Model-View-Controller. Then, I have explained the basic Employee details using the CRUD Operations like adding new employee details, updating or deleting existing employee details, and so on. Hope the article helps you to create the simple CRUD Application.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET MVC Example” was beneficial to you. You can view EDUCBA’s recommended articles for more information.