In the last ASP.NET post, we discussed Login and Registration in ASP.NET MVC using Entity Framework. In this ASP.NET post, we will learn CRUD Operations in MVC with Entity Framework without scaffolding. We can achieve the same task by using other connection methods like ADO.NET Connection, LINQ To SQL, SQLCommand, and stored procedure.
To understand how to insert, edit, update, and delete data in MVC, first, we insert records into the database, then select records from the database and bind them to the view. After that, we perform the edit and delete actions on the list. We will continue step by step for easy understanding.
This article is dedicated to new developers who want to insert, update, and delete records in an MVC application using Entity Framework.
MVC is a software design pattern used to develop user interfaces by dividing the program logic into three interconnected parts, similar to 3-tier architecture. This is done to separate the internal representation of information from the methods presented to and accepted by the user.
It provides fundamental components for designing programs for desktop or mobile, as well as web applications. This integrates well with object-oriented programming, as different models, views, and controllers can be treated as objects and reused within an application.
A model is the data used by a program. It can be a database, file, or a simple item, such as an icon or a character in a video game.
A view is a resource for displaying objects within an application. Examples include displaying a user creation page, video animations, buttons, or text. This encompasses anything that users can see.
A controller updates both the model and the view. It accepts input and implements related updates. For example, a controller can update a model by changing the attributes of a character in a video game. It can also modify the view by displaying the updated character in the game.
The three parts of MVC are interconnected. The view presents the model to the user. The controller accepts user input and updates the model and views accordingly. Although MVC does not mandate application design, many programming languages and IDEs support MVC architecture, making it a popular choice for developers.
So Let’s Start by creating a SQL table for performing the CRUD Operation.
SQL Script:
CREATE TABLE [dbo].[Company_Employee](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](150) NOT NULL,
[City] [nvarchar](500) NOT NULL,
[Salary] [decimal](18, 2) NOT NULL,
CONSTRAINT [PK_Employee_1] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CrudMvc.Models
{
using System;
using System.Collections.Generic;
public partial class Company_Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public decimal Salary { get; set; }
}
}
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View(db.Company_Employee.ToList());
}
}
Step 4-Now Right-click on Index ActionResult and add View for ActionMethod, Which Will show list of Company employees.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CrudMvc.Models;
namespace CrudMvc.Controllers
{
public class HomeController : Controller
{
private DemoDataBaseEntities db = new DemoDataBaseEntities();
// GET: Home
public ActionResult Index()
{
return View(db.Company_Employee.ToList());
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Step 6- Now, let's create the Index.cshtml view to display a list of records with edit and delete links, along with an add button for adding records.
@model IEnumerable<CrudMvc.Models.Company_Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.Salary)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
Step 7-Now, let's create action methods for adding, updating, and deleting, and create a view for each action method. Copy and paste the code below into the HomeController.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CrudMvc.Models;
namespace CrudMvc.Controllers
{
public class HomeController : Controller
{
private DemoDataBaseEntities db = new DemoDataBaseEntities();
// GET: Home
public ActionResult Index()
{
return View(db.Company_Employee.ToList());
}
// GET: Home/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company_Employee company_Employee = db.Company_Employee.Find(id);
if (company_Employee == null)
{
return HttpNotFound();
}
return View(company_Employee);
}
// GET: Home/Create
public ActionResult Create()
{
return View();
}
// POST: Home/Create
[HttpPost]
[ValidateAntiForgeryToken] // ValidateAntiForgeryToken is to protect from overposting attacks
public ActionResult Create([Bind(Include = "Id,Name,City,Salary")] Company_Employee company_Employee)
{
if (ModelState.IsValid)
{
db.Company_Employee.Add(company_Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(company_Employee);
}
// GET: Home/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company_Employee company_Employee = db.Company_Employee.Find(id);
if (company_Employee == null)
{
return HttpNotFound();
}
return View(company_Employee);
}
// POST: Home/Edit/5
[HttpPost]
[ValidateAntiForgeryToken] // ValidateAntiForgeryToken is to protect from overposting attacks
public ActionResult Edit([Bind(Include = "Id,Name,City,Salary")] Company_Employee company_Employee)
{
if (ModelState.IsValid)
{
db.Entry(company_Employee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(company_Employee);
}
// GET: Home/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company_Employee company_Employee = db.Company_Employee.Find(id);
if (company_Employee == null)
{
return HttpNotFound();
}
return View(company_Employee);
}
// POST: Home/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Company_Employee company_Employee = db.Company_Employee.Find(id);
db.Company_Employee.Remove(company_Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Step 8-Now create View for each ActionMethod for performing Operation
@model CrudMvc.Models.Company_Employee
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Company_Employee</h4>
<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.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</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>
@model CrudMvc.Models.Company_Employee
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Company_Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<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.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Salary, "", 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>
}
<div>
@Html.ActionLink("Back to List", "Index")
</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>
@model CrudMvc.Models.Company_Employee
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Company_Employee</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.City)
</dt>
<dd>
@Html.DisplayFor(model => model.City)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Salary)
</dt>
<dd>
@Html.DisplayFor(model => model.Salary)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
@model CrudMvc.Models.Company_Employee
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Company_Employee</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.City)
</dt>
<dd>
@Html.DisplayFor(model => model.City)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Salary)
</dt>
<dd>
@Html.DisplayFor(model => model.Salary)
</dd>
</dl>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Index")
</div>
}
</div>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CrudMvc.Models;
namespace CrudMvc.Controllers
{
public class Company_EmployeeController : Controller
{
private DemoDataBaseEntities db = new DemoDataBaseEntities();
// GET: Company_Employee
public ActionResult Index()
{
return View(db.Company_Employee.ToList());
}
// GET: Company_Employee/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company_Employee company_Employee = db.Company_Employee.Find(id);
if (company_Employee == null)
{
return HttpNotFound();
}
return View(company_Employee);
}
// GET: Company_Employee/Create
public ActionResult Create()
{
return View();
}
// POST: Company_Employee/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,City,Salary")] Company_Employee company_Employee)
{
if (ModelState.IsValid)
{
db.Company_Employee.Add(company_Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(company_Employee);
}
// GET: Company_Employee/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company_Employee company_Employee = db.Company_Employee.Find(id);
if (company_Employee == null)
{
return HttpNotFound();
}
return View(company_Employee);
}
// POST: Company_Employee/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,City,Salary")] Company_Employee company_Employee)
{
if (ModelState.IsValid)
{
db.Entry(company_Employee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(company_Employee);
}
// GET: Company_Employee/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company_Employee company_Employee = db.Company_Employee.Find(id);
if (company_Employee == null)
{
return HttpNotFound();
}
return View(company_Employee);
}
// POST: Company_Employee/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Company_Employee company_Employee = db.Company_Employee.Find(id);
db.Company_Employee.Remove(company_Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}