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

Crud Operations in MVC Using (DB First Approach)


ASP.NET MVC Database  Mvc4 
Ratings:
2 Comment(s)
 7937  View(s)
Rate this:

Crud Operations in MVC Using (DB First Approach)

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:

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.

 

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.

 

 

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:

 

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" )

 

 

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.

 

Now set your connection properties as in the following:

 

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

 

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.)

 

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”.

 

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.

 

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.

 

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".

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

 

HomeController.cs

using Crudinmvc.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace Crudinmvc.Controllers

{

    public class HomeController : Controller

    {

        NiitEntities db = new NiitEntities();

 

        public ActionResult Index()

        {

            return View(db.EmployeeDetails.ToList());

        }

 

        [HttpPost]

        public ActionResult Index(string name)

        {

            List<EmployeeDetail> emp = db.EmployeeDetails.Where(e => e.Name.Contains(name)).ToList();

            return View(emp);

        }

 

        public ActionResult Add()

        {

            return PartialView();

        }

 

        [HttpPost]

        public ActionResult 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");

        }

        public ActionResult Edit(int id)

        {

            return PartialView(db.EmployeeDetails.Find(id));

        }

 

        [HttpPost]

        public ActionResult 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");

        }

        public ActionResult 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

<link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

<script src="~/Scripts/jquery-2.1.1.min.js"></script>

<script src="~/Scripts/bootstrap/js/bootstrap.min.js"></script>

 

@model IList<Crudinmvc.Models.EmployeeDetail>

@{

    ViewBag.Title = "Index";

}

<div id="div-main">

    <link href="~/Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

    <link href="~/Content/bootstrap/css/bootstrap-table.css" rel="stylesheet" />

    <script src="~/Scripts/jquery-2.1.1.min.js"></script>

    <script src="~/Scripts/bootstrap/js/bootstrap.min.js"></script>

    <script src="~/Scripts/app.js"></script>

    <br />

    <br />

    <div class="container">

        <div class="row">

            <div class="col-md-6">

                <select class="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>

            <div class="col-md-5">

                <div class="input-group">

                    <span class="input-group-addon" id="basic-addon1" style="cursor: pointer;"><i class="glyphicon glyphicon-search"></i></span>

                    <input type="text" id="search-box" class="form-control" placeholder="Search by Name" aria-describedby="basic-addon1">

                </div>

            </div>

            <div class="col-md-1 text-info">

                <a href="@Url.Action("Add", "Home")" id="add"><i class="glyphicon glyphicon-plus" style="font-size: 30px; cursor: pointer;"></i></a>

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-12">

                <div class="table-responsive">

                    <table class="table table-bordered table-striped">

                        <thead>

                            <tr class="success">

                                <th class="text-center">ID</th>

                                <th class="text-center">Name</th>

                                <th class="text-center">Email ID</th>

                                <th class="text-center">Address</th>

                                <th class="text-center">City</th>

                                <th class="text-center">Contact No</th>

                                <th class="text-center">Edit</th>

                                <th class="text-center">Delete</th>

                            </tr>

                        </thead>

                        <tbody>

                            @foreach (var item in Model)

                            {

                                <tr>

                                    <td class="id">@item.ID</td>

                                    <td>@item.Name</td>

                                    <td>@item.EmailID</td>

                                    <td>@item.Address</td>

                                    <td>@item.City</td>

                                    <td>@item.ContactNO</td>

                                    <td class="text-center"><a href="@Url.Action("Edit", "Home", new { @id = @item.ID })" class="openDialog-Edit"><i class="glyphicon glyphicon-edit" style="cursor: pointer;"></i></a></td>

                                    <td class="text-center"><a href="@Url.Action("Delete", "Home", new { @id = @item.ID })"><i class="glyphicon glyphicon-trash" style="cursor: pointer;"></i></a></td>

                                </tr>

                            }

                        </tbody>

                    </table>

                </div>

            </div>

        </div>

    </div>

 

 

    <div class="modal fade" id="addmodel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                    <h4 class="modal-title" id="myModalLabel">Add User Details</h4>

                </div>

                <div class="divForAdd">

                </div>

            </div>

        </div>

    </div>

 

    <div class="modal fade" id="editmodel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                    <h4 class="modal-title">Update User Details</h4>

                </div>

                <div class="divForCreate">

                </div>

            </div>

        </div>

    </div>

</div>

Partail view:- Add.cshtml

@model Crudinmvc.Models.EmployeeDetail

 

 

@using (Html.BeginForm("Add", "Home", FormMethod.Post))

{

    <div class="modal-body">

        <div class="row">

            <div class="col-md-4">

                Name

            </div>

            <div class="col-md-8">

                @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4">

                Email ID

            </div>

            <div class="col-md-8">

                @Html.TextBoxFor(m => m.EmailID, new { @class = "form-control" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4">

                Address

            </div>

            <div class="col-md-8">

                @Html.TextAreaFor(m => m.Address, new { @class = "form-control" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4">

                City

            </div>

            <div class="col-md-8">

                @Html.TextBoxFor(m => m.City, new { @class = "form-control" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4">

                Contact No

            </div>

            <div class="col-md-8">

                @Html.TextBoxFor(m => m.ContactNO, new { @class = "form-control" })

            </div>

        </div>

    </div>

    <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="submit" class="btn btn-primary">Save</button>

    </div>

}

 

Partial view:- Edit.cshtml

@model Crudinmvc.Models.EmployeeDetail

 

 

@using (Html.BeginForm("Edit", "Home", FormMethod.Post))

{

    <div class="modal-body">

        <div class="row">

            <div class="col-md-4">

                Name

            </div>

            <div class="col-md-8">

                @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4">

                Email ID

            </div>

            <div class="col-md-8">

                @Html.TextBoxFor(m => m.EmailID, new { @class = "form-control" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4">

                Address

            </div>

            <div class="col-md-8">

                @Html.TextAreaFor(m => m.Address, new { @class = "form-control" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4">

                City

            </div>

            <div class="col-md-8">

                @Html.TextBoxFor(m => m.City, new { @class = "form-control" })

            </div>

        </div>

        <div class="clearfix">&nbsp;</div>

        <div class="row">

            <div class="col-md-4">

                Contact No

            </div>

            <div class="col-md-8">

                @Html.TextBoxFor(m => m.ContactNO, new { @class = "form-control" })

            </div>

        </div>

    </div>

    <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="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

 

Output 2:

When Click on Add icon

 

Output 3:

When Click on Edit icon

 

 

Output 4:

When Click on Deletet icon

After click delete

Output 5:

When Click on Search icon put string “kamlakar”

 

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

 


Download

By Mohammed Shoukat on   one year ago
Please send the source code of Crud Operations in MVC Using (DB First Approach)
Thanks.

Please send me source code

By dineshkumar shan on   4 months ago
Hi,

Please send me source code .

Don't want to miss updates? Please click the below button!

Follow MindStick