In the last asp.net post, we have discussed Login and Registration in Asp .net MVC using Entity Framework.In this asp.net post, we will learn Crud Operation in MVC with Entity Framework Without Scaffolding.we can do the same task by using other connection methods like Ado .Net Connection, LINQ To SQL and SQLCommand and stored procedure.
To understand insert edit update and delete data in MVC, First, we insert records into the database and select records from the database and bind to View, then perform the edit and delete action in the list.we will continue step by step for easy understanding.
This article is dedicated to new developer wants to insert, update, and delete records in an MVC Application using Entity Framework.
Asp .Net Mvc
MVC is a software design pattern that is used to develop user interfaces that divide the respective program logic into three interrelated parts just like 3 tier architecture. This is done to separate the internal representation of information from the methods presented and accepted by the user.
It provides original pieces to design a program for desktop or mobile, as well as web applications. This works well with object-oriented programming, as different models, views, and controllers can be treated as objects and reused within an application.
1. Model
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.
2.View
A view is a resource for displaying objects within an application. Examples include displaying a user create page,Video Animation or buttons or text. This includes anything that users can see.
3.The controller
A controller updates both the model and the idea. It accepts the input and makes related updates. For example, a controller can update a model by changing the characteristics of a character in a video game. It can modify the view by displaying the updated character in the game.
The three parts of the MVC are interlinked. The view displays the model for the user. The controller accepts user input and updates the model and views accordingly. While MVC does not require application design, many programming languages and IDEs support MVC Architecture, making it a common option for developers.
Crud Operation Without Scaffolding
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 Index.cshtml View showing list of records with edit and delete the link and with an add button for adding records.
Index.cshtml
@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 an action method for adding, updating, and deleting and create a View for each action method. Copy-paste the below code in 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
Create.cshtml
@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>
Edit.cshtml
@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>
Details.cshtml
@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>
Delete.cshtml
@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>
Result –
Crud Operation in MVC with Entity Framework Using Scaffolding
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);
}
}
}
The post Insert ,Update,Delete in MVC with Entity Framework appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- how to create an audit trail with Entity framework 5 and MVC 4
- MVC and Entity Framework Html.DisplayNameFor with Composite ViewModel
- Is This How to Create a Data Transfer Object (DTO) with Entity Framework Core & ASP.NET Core MVC 2.2+ and 3.0
- Entity Framework and the relationship with MVC
- How do I ensure an idempotent database insert with Entity Framework 5?
- Entity Framework with Owin DbContext per request in MVC
- Using Include in Entity Framework 4 with lambda expressions
- How to sync model after using Code First from Database using Entity Framework 6.1 and MVC 5?
- Entity Framework Code First AddOrUpdate method insert Duplicate values
- Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'
- Entity Framework with XML Files
- LIKE query with Entity Framework
- No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'.
- Repository Pattern with Entity Framework 4.1 and Parent/Child Relationships
- Exclude a field/property from the database with Entity Framework 4 & Code-First
- MVC scaffolding does not support Entity Framework 6 or later
- How to use an existing enum with Entity Framework DB First
- Loading all the children entities with entity framework
- Using TransactionScope with Entity Framework 6
- Use Entity framework code first with nosql database
- Adding a controller with read/write actions and views, using Entity Framework - what is "Data Context class"?
- Loading Nested Entities / Collections with Entity Framework
- Insert new entity to context with identity primary key
- Entity Framework not working with temporal table
- The data reader is incompatible with the specified Entity Framework
- SqlBulkCopy Multiple Tables Insert under single Transaction OR Bulk Insert Operation between Entity Framework and Classic Ado.net
- Updating records using a Repository Pattern with Entity Framework 6
- Snapshot History With Entity Framework
- Entity Framework with Sql Server Column Level Encryption
- Authentication and Authorization without Entity Framework in ASP.NET 5 MVC 6
- TPIN number validation in java, c++ or c#
- Call fortran code from c#
- Liquid layout in WPF?
- CheckedListbox Displaymember and ValueMember
- Dictionary methods Remove and Clear (.NET Core) modify the collection during enumeration. No exception thrown
- How to get installation path of an application?
- Error message Nullable object must have a value
- StructureMap -> EnrichWith is enriching too much (other instances)
- Xamarin 'Resource.Layout' does not contain a definition for 'Tabbar' error
- Add Control Value before another Control value in C#
- Microsoft.Threading.Tasks not found
- Is there a type-safe ordered dictionary alternative?
- How to format Visual Studio XML documentation for display on the web
- GetType().ToString() Returns Unexpected Characters
- Why is the To property of .net's MailMessage class read-only?
- Get the maximum time of a date
- How to pin an 'unmanaged' pointer?
- Should member variables in singleton be declared as static?
- How to read HttpResponseMessage content as text
- Is there any alternate way to processing DICOM images using WPF in C# without any third party/Library?