articles

Home / DeveloperSection / Articles / Crud Operations in MVC Using (DB First Approach)

Crud Operations in MVC Using (DB First Approach)

Anonymous User28027 16-Jan-2015

Hi everyone in this article I’m explaining about crud operation in mvc.


This article will take you on a journey of MVC Create, Update and Delete (CRUD) operations. I'll show you step-by-step operations using simple images and charts. So buckle up for that journey.


Agenda

  • Overview
  • Introduction
  • Procedure
    • Creating a MVC Project
    • Adding EDM
    • DB Settings
    • Adding a controller
    • (Ref code Snippet)

Overview

This article will explain MVC base operations rather than any fundamentals and anything like that so if you are new to MVC then I'll suggest you first explore the basics, it will hardly take a few hours then you can read this article.

In spite of these entire one more thing, I'm using MVC4 here for these operations. You can use any version but in the earlier versions, like in case of VS'8 and below you need to install templates first, then you can have fun.

Introduction

This article is all about ASP.NET MVC CRUD operations using Entity Data Model (DB First Approach). This will explain it in baby steps using images.

Procedure

I am dividing this into 5 major steps, these steps will contain several sub steps. The major steps of this project are:

1.     Creating a Project

2.     Adding EDM

3.     DB Settings

4.     Adding Controller

5.     Adding View and partial view

Step 1:  Create a MVC Project

Just click on File > New project.

On clicking New Project you will get a window like this, in that window does these

tiny steps:

Crud Operations in MVC Using (DB First Approach)

In this window simply fill in the project name depending on you; in my case it is "Crudinmvc" and then click on OK.

On clicking OK a window like this will pop up on your screen.

Crud Operations in MVC Using (DB First Approach)

 

In that window from Project Templates you have several options like:


1.       Empty

(Simply a blank view)

2.       Basic

(Contains a few options and a few folders)

3.       Internet Template

(Contains all the folders for global use)

4.       Intranet Template

(Contains all the folders but for a specific scenario)

5.       Mobile Application

(For mobile app dev)

6.       Web API

(Extra features of Razor, Routing and others)

7.       Single Page Application

(For single page app dev)

8.       Facebook Application

(Facebook app dev)

From those select Empty and then from View Engine select Razor Engine View (it's

the default actually).

Then after View Engine there is an option for Create a Unit Test Project, this option

is for creating a step-wise unit test for your project.

Now just create a Test Project and click OK.

On clicking okay it will take a while to create the project.

Then you will get a window containing these folders:

  • Solution Explorer
  • Test Explore
  • Class View
  • Properties

From these options select Solution Explorer, click Crudinmvc, just click on that and

you will get a view of this window.

Crud Operations in MVC Using (DB First Approach)

 

 

Step 2:  Adding EDM

(For data I am selecting ADO.Net Entity Data Model, you can select several other

available options.)

Just do this procedure, right-click on CRUDoperation > Add New Item

Then follow this procedure, respectively:

Crud Operations in MVC Using (DB First Approach)

 

Simply name your EDM EmployeeDetails (in my case it's EDM) and then click OK.

Now you will get a pop-up window, named Choose Model Contents. This contains

the following 2 types of model contents:

  • Generate from Database (DB first approach)
  • Empty Model (Modal first approach)

(In my case I am using the DB first approach (Generate from Database), just select

it and click on "Next" )

 

Crud Operations in MVC Using (DB First Approach)

 

On clicking Next, you will get a option Choose Your Data Connection, from here

just select a connection string if you already have one or else you can go with New

Connection.

Just click on New Connection.

 

Crud Operations in MVC Using (DB First Approach)

Now set your connection properties as in the following:

Crud Operations in MVC Using (DB First Approach)

 

Just fill in all the required details of your server and database and proceed further.

Crud Operations in MVC Using (DB First Approach)

 

Microsoft has provided a beautiful option to check your connection, down the pop

box. Just click on Test Connection, if everything until now will be smooth and clear

then you will get a pop-up box saying- "Test connection Succeeded" as shown

below.

(Otherwise you need to recheck your DB and server details again and try to

establish the connection again and then you can check your connection.)

Crud Operations in MVC Using (DB First Approach)

 

Now you can see the generated Data Connection in the box as shown below. Just

select a few further settings like Security and March forward.

Just click on “Finish”.

Crud Operations in MVC Using (DB First Approach)

 

On clicking Finish it will show a box saying Model Wizard, just select any of the

wizards depending on availability (in my case I am selecting Entity Framework 5.0).

Click Next for further settings.

Step 3: Selecting you DB Settings

Now in this step just click on Table, dbo (as I already have a table in my DB, but if

you created a Stored Procedure or view then select it respectively).

In model Namespace just leave it as it is or change it depending on you. In my case

its TestDBModel, click Finish.

Crud Operations in MVC Using (DB First Approach)

 

This will redirect you to a page containing a structure diagram of all the available

tables in that select DB in step 3. You remove others depending on you (in my case

it's Employee having the columns EmployeeId, FirstName, LastName, Age, Project

and Address).

You don't need to do anything here, just chill it's more than half done.

Crud Operations in MVC Using (DB First Approach)

 

You can see all these EDM files in the Solution Explorer, having all the required

fields, pages and reference files of all your available tables with ".cs extension".

Crud Operations in MVC Using (DB First Approach)

Note: Before proceeding to Step 5, build the project. It's recommended.

Step 4: Adding a Controller

Add home controller Right click on controller >> Add >> Controller

Give the controller name in my case Controller name HomeController

Select template name in my case Empty MVC Controller and click add

Crud Operations in MVC Using (DB First Approach)

 

HomeController.cs

using Crudinmvc.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Crudinmvc.Controllers
{
    publicclassHomeController : Controller
    {
        NiitEntities db = newNiitEntities();
 
        publicActionResult Index()
        {
            return View(db.EmployeeDetails.ToList());
        }
 
        [HttpPost]
        publicActionResult Index(string name)
        {
            List<EmployeeDetail> emp = db.EmployeeDetails.Where(e => e.Name.Contains(name)).ToList();
            return View(emp);
        }
 
        publicActionResult Add()
        {
            return PartialView();
        }
 
        [HttpPost]
        publicActionResult Add(EmployeeDetail model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    db.EmployeeDetails.Add(model);
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    TempData["Failure"] = ex;
                }
            }
            else
            {
                TempData["Failure"] = "Record Not Saved";
            }
            return RedirectToAction("Index");
        }
        publicActionResult Edit(int id)
        {
            return PartialView(db.EmployeeDetails.Find(id));
        }
 
        [HttpPost]
        publicActionResult Edit(EmployeeDetail model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    db.EmployeeDetails.Add(model);
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    TempData["Failure"] = ex;
                }
            }
            else
            {
                TempData["Failure"] = "Record Not Saved";
            }
            return RedirectToAction("Index");
        }
        publicActionResult Delete(int id)
        {
            db.EmployeeDetails.Remove(db.EmployeeDetails.Find(id));
            db.SaveChanges();
            return RedirectToAction("Index");
        }
 
    }
}

 

Step 5: Adding a View and partial view

View:- Index.cshtml

Download these file 3 files for open model and good looking ui

<linkhref="~/Content/bootstrap/css/bootstrap.min.css"rel="stylesheet"/>
<scriptsrc="~/Scripts/jquery-2.1.1.min.js"></script>
<scriptsrc="~/Scripts/bootstrap/js/bootstrap.min.js"></script>
 
@model IList<Crudinmvc.Models.EmployeeDetail>
@{
    ViewBag.Title = "Index";
}
<divid="div-main">
    <linkhref="~/Content/bootstrap/css/bootstrap.min.css"rel="stylesheet"/>
    <linkhref="~/Content/bootstrap/css/bootstrap-table.css"rel="stylesheet"/>
    <scriptsrc="~/Scripts/jquery-2.1.1.min.js"></script>
    <scriptsrc="~/Scripts/bootstrap/js/bootstrap.min.js"></script>
    <scriptsrc="~/Scripts/app.js"></script>
    <br/>
    <br/>
    <divclass="container">
        <divclass="row">
            <divclass="col-md-6">
                <selectclass="form-control">
                    <option>---select---</option>
                    <option>1-5</option>
                    <option>1-10</option>
                    <option>1-15</option>
                    <option>1-20</option>
                    <option>1-25</option>
                    <option>1-30</option>
                    <option>1-35</option>
                    <option>1-40</option>
                    <option>1-45</option>
                    <option>1-50</option>
                </select>
            </div>
            <divclass="col-md-5">
                <divclass="input-group">
                    <spanclass="input-group-addon"id="basic-addon1"style="cursor: pointer;"><iclass="glyphicon glyphicon-search"></i></span>
                    <inputtype="text"id="search-box"class="form-control"placeholder="Search by Name"aria-describedby="basic-addon1">
                </div>
            </div>
            <divclass="col-md-1 text-info">
                <ahref="@Url.Action("Add", "Home")"id="add"><iclass="glyphicon glyphicon-plus"style="font-size: 30px; cursor: pointer;"></i></a>
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-12">
                <divclass="table-responsive">
                    <tableclass="table table-bordered table-striped">
                        <thead>
                            <trclass="success">
                                <thclass="text-center">ID</th>
                                <thclass="text-center">Name</th>
                                <thclass="text-center">Email ID</th>
                                <thclass="text-center">Address</th>
                                <thclass="text-center">City</th>
                                <thclass="text-center">Contact No</th>
                                <thclass="text-center">Edit</th>
                                <thclass="text-center">Delete</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var item in Model)
                            {
                                <tr>
                                    <tdclass="id">@item.ID</td>
                                    <td>@item.Name</td>
                                    <td>@item.EmailID</td>
                                    <td>@item.Address</td>
                                    <td>@item.City</td>
                                    <td>@item.ContactNO</td>
                                    <tdclass="text-center"><ahref="@Url.Action("Edit", "Home", new { @id = @item.ID })"class="openDialog-Edit"><iclass="glyphicon glyphicon-edit"style="cursor: pointer;"></i></a></td>
                                    <tdclass="text-center"><ahref="@Url.Action("Delete", "Home", new { @id = @item.ID })"><iclass="glyphicon glyphicon-trash"style="cursor: pointer;"></i></a></td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
 
 
    <divclass="modal fade"id="addmodel"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true">
        <divclass="modal-dialog">
            <divclass="modal-content">
                <divclass="modal-header">
                    <buttontype="button"class="close"data-dismiss="modal"aria-label="Close"><spanaria-hidden="true">&times;</span></button>
                    <h4class="modal-title"id="myModalLabel">Add User Details</h4>
                </div>
                <divclass="divForAdd">
                </div>
            </div>
        </div>
    </div>
 
    <divclass="modal fade"id="editmodel"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true">
        <divclass="modal-dialog">
            <divclass="modal-content">
                <divclass="modal-header">
                    <buttontype="button"class="close"data-dismiss="modal"aria-label="Close"><spanaria-hidden="true">&times;</span></button>
                    <h4class="modal-title">Update User Details</h4>
                </div>
                <divclass="divForCreate">
                </div>
            </div>
        </div>
    </div>
</div>


Partail view:- Add.cshtml

@model Crudinmvc.Models.EmployeeDetail
 
 
@using (Html.BeginForm("Add", "Home", FormMethod.Post))
{
    <divclass="modal-body">
        <divclass="row">
            <divclass="col-md-4">
                Name
            </div>
            <divclass="col-md-8">
                @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4">
                Email ID
            </div>
            <divclass="col-md-8">
                @Html.TextBoxFor(m => m.EmailID, new { @class = "form-control" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4">
                Address
            </div>
            <divclass="col-md-8">
                @Html.TextAreaFor(m => m.Address, new { @class = "form-control" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4">
                City
            </div>
            <divclass="col-md-8">
                @Html.TextBoxFor(m => m.City, new { @class = "form-control" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4">
                Contact No
            </div>
            <divclass="col-md-8">
                @Html.TextBoxFor(m => m.ContactNO, new { @class = "form-control" })
            </div>
        </div>
    </div>
    <divclass="modal-footer">
        <buttontype="button"class="btn btn-default"data-dismiss="modal">Close</button>
        <buttontype="submit"class="btn btn-primary">Save</button>
    </div>
}

 

Partial view:- Edit.cshtml

@model Crudinmvc.Models.EmployeeDetail
 
 
@using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
    <divclass="modal-body">
        <divclass="row">
            <divclass="col-md-4">
                Name
            </div>
            <divclass="col-md-8">
                @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4">
                Email ID
            </div>
            <divclass="col-md-8">
                @Html.TextBoxFor(m => m.EmailID, new { @class = "form-control" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4">
                Address
            </div>
            <divclass="col-md-8">
                @Html.TextAreaFor(m => m.Address, new { @class = "form-control" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4">
                City
            </div>
            <divclass="col-md-8">
                @Html.TextBoxFor(m => m.City, new { @class = "form-control" })
            </div>
        </div>
        <divclass="clearfix">&nbsp;</div>
        <divclass="row">
            <divclass="col-md-4">
                Contact No
            </div>
            <divclass="col-md-8">
                @Html.TextBoxFor(m => m.ContactNO, new { @class = "form-control" })
            </div>
        </div>
    </div>
    <divclass="modal-footer">
        <buttontype="button"class="btn btn-default"data-dismiss="modal">Close</button>
        <buttontype="submit"class="btn btn-primary">Update</button>
    </div>
}
 

App.js

$(document).ready(function () {
    $('#add').click(function (event) {
        event.preventDefault();
        $.get(this.href, function (response) {
            $('.divForAdd').html(response);
        });
        $('#addmodel').modal({
            backdrop: 'static',
        }, 'show');
    });
 
    $('.openDialog-Edit').click(function (event) {
        event.preventDefault();
        $.get(this.href, function (response) {
            $('.divForCreate').html(response);
        });
        $('#editmodel').modal({
            backdrop: 'static',
        }, 'show');
    });
 
 
    $('#basic-addon1').click(function (e) {
        var name = $('#search-box').val();
        e.preventDefault(); // <------------------ stop default behaviour of button
        $.ajax({
            url: "/Home/Index",
            type: "POST",
            data: { 'Name': name },
            success: function (data) {
                $('#div-main').html(data);
            },
            error: function () {
                alert("An error has occured!!!");
            }
        });
    });
 
});

 

 

Output 1:

When application run first time

Crud Operations in MVC Using (DB First Approach)

 

Output 2:

When Click on Add icon

Crud Operations in MVC Using (DB First Approach)

 

Output 3:

When Click on Edit icon

Crud Operations in MVC Using (DB First Approach)

 

 

Output 4:

When Click on Deletet icon

Crud Operations in MVC Using (DB First Approach)

After click delete

Crud Operations in MVC Using (DB First Approach)

Output 5:

When Click on Search icon put string “kamlakar”

Crud Operations in MVC Using (DB First Approach)

 

 In my previous post i'll explain about CSS Image Caption

 


Updated 23-Nov-2019
I am a content writter !

Leave Comment

Comments

Liked By