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#
- Entity Framework Code First with MVC : RuntimeBinder Exception error
- How to insert data row using Entity Framework with Auto Increment column
- The INSERT statement conflicted with the FOREIGN KEY constraint in Entity Framework database first
- Cannot connect to order Oracle database with Entity Framework in ASP.NET MVC
- Cannot connect to order Oracle database with Entity Framework in ASP.NET MVC
- Entity Framework bulk insert with transaction management - Performance
- How to call stored procedure in ASP.NET MVC with Entity Framework
- ASP.NET MVC with Entity Framework Context on separate project. Invalid operation. The connection is closed
- ASP.NET MVC with Entity Framework Context on separate project. Invalid operation. The connection is closed
- Unable to Insert with Entity Framework
- ProviderIncompatibleException with Code First Entity Framework - MVC 4
- How to ActionResult Edit in MVC using Entity Framework with two tables (one to one)?
- How to ActionResult Edit in MVC using Entity Framework with two tables (one to one)?
- Entity Framework Returns No Value With MVC Action
- How to use Identity with Entity Framework database first in ASP.NET MVC
- Entity Framework says I'm trying to insert multiple entities with the same key, but I don't think I am
- Facing issue with entity framework insert to Db
- .Include() doen't work properly for retriving properties in ASP.NET MVC 5 app with Entity Framework
- How to upload multiple files in mvc 5 to server and store file's path with Entity Framework
- Entity Framework with MySQL connector in c#
- Association inheritance with Entity Framework
- Error : Package restore failed when creating a new controller using view with Entity Framework
- Checking if a record exist returns "Sequence contains more than one matching element." for Net5 with Entity Framework 5
- Entity Framework In Memory Database With Tests Fail Only When Running Tests In Series
- Update parent record along with child record - entity framework core
- C# conditional operator with Entity Framework appears to be evaluating both expressions
- ASP.NET MVC / Entity Framework - Controller generation is somehow using old properties
- Entity Framework Core (Code First) won't insert into dependent tables
- How do you do fulltext search add two field with Entity Framework Core?
- What version of Entity Framework is packaged with .Net Standard 2.1?
- ServiceM8 Development in C# (Contact Details and job sync)
- TSV file converts string into numbers
- navPage.SetHideNavigationBarSeparator(true) no longer works in Xamarin 4.5 latest any solution for that, not working the below code
- How to get DataTable from JSON string that contains an empty array using JsonConvert?
- Error while uploading the image to Azure Blob from a cordova application
- Problem with brackets in regular expression in C#
- Using C# .Net Core, how do I pass the contents of a textbox to a modal
- Why syncfusions DomainUpDown control not visible in wpf?
- Detect first letter in textbox then appears in gridview
- Upgrading Parameterised Webdriver Test to Nunit 3.0
- How to make a c# console app .exe to open a save dialog to save a file generated by the app?
- How can i create a directory for each name that it's code belong to?
- WebAPI not accepting Post Requests Successfully
- Getting httpresponse from other site
- Printing from Datecs FML 10KL
- ways to improve the time of the execution - Data structures
- Adding Group totals to a different section of an SSRS report
- No mapping for the Unicode character Exception
- The underlying provider failed on Open at the time Unity resolve the dependencies
- Properties of IWebElement are not visible in VisualStudio 2013