Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

ASP.NET MVC Example

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.

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 GetAllEmployees()
{
connection();
List EmpList = new List();
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()


Add Employee



@Html.ActionLink("Back to Employee List", "GetAllEmpDetails")



@Html.ValidationSummary(true, "", new { @class = "text-danger" })

@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })



@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })



@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })









@ViewBag.Message



}


GetAllEmpDetails.cshtml

@model IEnumerable


@Html.ActionLink("Add New Employee", "AddEmployee")









@foreach (var item in Model)
{
@Html.HiddenFor(model => item.Empid)






}

@Html.DisplayNameFor(model => model.Name)

@Html.DisplayNameFor(model => model.City)

@Html.DisplayNameFor(model => model.Address)

@Html.DisplayFor(modelItem => item.Name)

@Html.DisplayFor(modelItem => item.City)

@Html.DisplayFor(modelItem => item.Address)

@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?');" })

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

This is a guide to ASP.NET MVC Example. Here we discuss the sample application of ASP.NET MVC, which consists of three Folders of Model-View-Controller. You may also look at the following articles to learn more –

  1. ASP.NET Core Session
  2. ASP.NET Core JWT
  3. ASP.NET UpdatePanel
  4. ASP.NET ViewState

The post ASP.NET MVC Example appeared first on EDUCBA.



This post first appeared on Best Online Training & Video Courses | EduCBA, please read the originial post: here

Share the post

ASP.NET MVC Example

×

Subscribe to Best Online Training & Video Courses | Educba

Get updates delivered right to your inbox!

Thank you for your subscription

×