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]

 

Step 1-Add MVC Project,Open your Microsoft Visual Studio ,Now, click on File =>New Project =>click on Visual C# =>select ASP.NET Web Application, Empty, and click on OK.
Step 2-Right-click on the Model folder and add a new item =>select Ado .net entity data model and perform the steps mention in the below image.
It will create a data model class for the table which we will as Model Class for the View
//------------------------------------------------------------------------------
// <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; }
    }
}
Step 3-Right-click on the Controller folder and add an empty controller for performing Crud Operation.
I have added a HomeController in Our Project and you can give your choice name.
 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.

Step 5-Let’s write the logic for Index ActionMethod so that It will return the 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

If you want to perform the crud operation with entity framework using scaffolding. Then follow the below steps it is very required a few steps. It will generate code views for you automatically.

Right click on Controller folder=>select add controller =>select Controller with read/write action.

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