Sunday 7 August 2016

Simple CRUD( Create, Read, Update or Delete) Operation with MVC5 Using Entity Data Model

MVC CRUD Operation using Entity Data Model or Database First Approach

CRUD : - Create, Read/Retrieve, Update and Delete or you can say Insert, Update, Select and Delete

So let's start with quick revision!

Model : Model is responsible for maintaining the data, here we write data access logics,
business access logics & we also maintain the Validations in model

View : View is responsible for displaying the data.

Controller : Controller is Responsible for any new request which has comes by user.  Controller identify the request and send to them relevant action.

Steps are

  • Open Visual studio 2015
  • Go to file  >  New  > Project  



  • Select ASP.Net Web Application
  • Give Name to Application > ok















Now solution has been created successfully.

Before starting, create tables in sql. Use below query for create table.

CREATE TABLE [dbo].[RegistrationDetails]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[MobileNo] [varchar](50) NULL,
[EmailID] [varchar](50) NULL,
[Age] [varchar](10) NULL,
[Address] [varchar](50) NULL,
 CONSTRAINT [PK_RegistrationDetails] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


Now we will create Connection with Entity Data Model:

Steps are :

Right click on Model Folder > Add > New Item > In Left Pane  select Data > ADO.Net Entity Data Model> Give Name( Model1)> Add

select  EF Designer from Database > Next > New Connection >



How to Know about your SQL Server name?? dont worry it is very easy to find out.
Let's see..

Open Sql Server > Right Click on Left Icon see below image > Properties





Copy server name  and paste into place of server name, see below image for ref.

Paste server name > Select database name > Ok






Here dataEntities is your connection name , click on next.
Now, we will select table name which we want to use, like our table name is RegistrationDetails


Select table Name, see below image 


select table name and then click on finish.


Note :  In MVC, we works with object and class.  Model converts our table into class and table column  name  into Properties.  see below image for Ref .



Now connection has been created successfully.


Now we will create Controller  

In Controller we will write Action for each request like Insert, update, delete...

Steps are  :
  • Right click on Controller Folder
  • Add > Controller >  MVC 5 Controller - Empty > Add








Give name to controller like above image Registration.
Note :
In above screenshot highlighted text controller comes by default so don't remove it, its represents Registration is Controller, so don't remove it other it will not work.

After Adding Controller 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace sandeepcodes.Controllers
{
    public class RegistrationController : Controller
    {
        // GET: Registration
        public ActionResult Index()
        {
            return View();
        }
    }
}

Now we will Create Action for Insert and View page for Insert


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace sandeepcodes.Controllers
{
    public class RegistrationController : Controller
    {
        // GET: Registration
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Insert()
        {
            return View();
        }

    }

}

Now how to add view for Insert Action :

Right click on Action > Add View > View name should be same as Action name, don't change it.
See below screenshot for ref  :-



Note :

When we add controller then automatically one folder has created inside of View Folder same name as Controller name. It represents this is controller view folder. 

How to find out your View??

Goto view folder> Registration Folder> Your view(Insert), see below screen shot


Open your view page Click on Insert.cshtml

and write below code


@model sandeepcodes.Models.RegistrationDetail
@{
    ViewBag.Title = "Registration Form";
}
<h2>Insert</h2>

@using (Html.BeginForm("Insert", "Registration", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{

    <div>
        <div style="width:300px">
            @Html.LabelFor(x => x.Name)
            @Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
            
        </div>

        <div style="width:300px">
            @Html.LabelFor(x => x.MobileNo)
            @Html.TextBoxFor(x => x.MobileNo, new { @class = "form-control" })
        </div>

        <div style="width:300px">
            @Html.LabelFor(x => x.EmailID)
            @Html.TextBoxFor(x => x.EmailID, new { @class = "form-control" })

        </div>

        <div style="width:300px">
            @Html.LabelFor(x => x.Age)
            @Html.TextBoxFor(x => x.Age, new { @class = "form-control" })
        </div>

        <div style="width:300px">
            @Html.LabelFor(x => x.Address)
            @Html.TextBoxFor(x => x.Address, new { @class = "form-control" })
        </div>
        <div align="left">
            <br />
            <input type="submit" name="save" class="btn btn-success" value="Save" />
        </div>
</div>
}


Note :
Add below line code into your view page, here we gives path of our class RegistrationDetail to view with the help of this view will inherit the class fileds.

@model sandeepcodes.Models.RegistrationDetail

In above code  : -  sandeepcodes is my solution name and RegistrationDetail is my Class name which is inside of Model Folder

@using (Html.BeginForm("Insert", "Registration", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))

In above code we are going to submit data that's why we are using Form Method is Post
Insert : - Insert is Action name on Controller Page
Registration : - Registration in Controller name
 ( So change name according to you code which you write)

Now Run Your Application :-

Open View Page Insert.cshtml and Click on Run command, view will look like :-


Now Display part has been ready now we will work on Submit Data, so go to Controller and we will create Post Properties for Insert Action.

Note 

We are going to submit data into database now we need to connection file name, so add reference of connection file

using sandeepcodes.Models;//  Add ref of Model

Create object of Connection File 

dataEntities db = new dataEntities(); // Create Connection

See code below : -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using sandeepcodes.Models;//  Add ref of Model

namespace sandeepcodes.Controllers
{
    public class RegistrationController : Controller
    {

        dataEntities db = new dataEntities(); // Create Connection
        // GET: Registration
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Insert()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Insert(RegistrationDetail obj)
        {
   
                db.RegistrationDetails.Add(obj);
                db.SaveChanges();  
                return RedirectToAction("Insert", "Registration");
        }

    }


}


In above code we create new Post Action(Insert) with same name as Get action (Insert). By default Action has Get Property.
  public ActionResult Insert(RegistrationDetail obj)  :  Here RegistrationDetails is class name .

Build Your Solution and Run the application.

Output of My submission form :




Now How we will Read Data/ Bind Data or you can say display data in MVC??


Dont worry, it is very easy.  Let's follow the below steps :-


Now we will Add Action for Read/ Show/ Details

Add Details() Action in Registration Controller


 public ActionResult Details()
        {
            var list = db.RegistrationDetails.ToList();
            return View(list);
        }

Here we will use .ToList() to show all records in List Format.
We are going to show data from database so we don't need to write [HttpGet] method, because by default Action has Get.

Now we will create view for Details Action

Follow same steps like Insert Action...

Right Click on Details() Action > Add View

View Name should be same as Action Name.

Now open Details.cshtml view page and write below code

@using sandeepcodes.Models
    @{
        ViewBag.Title = "Details";
    }

    <h2>Details</h2>


    <div>

        <table class="table table-striped table-hover" style="width:800px; border:1px solid #cdcdcd">
            <tr>
                <td>Name</td>
                <td>MobileNo</td>
                <td>Address</td>
                <td>Age</td>
                <td>Email</td>
            </tr>
             @foreach (RegistrationDetail item in Model)
             {
                <tr>
                    <td width="100px">@item.Name</td>
                    <td>@item.MobileNo</td>
                    <td>@item.Address</td>
                    <td>@item.Age</td>
                    <td>@item.EmailID</td>
                </tr>
             }


    </table>

</div>

Note : 

  •  we are using foreach loop to bind data in table, for loop execute till last record.


  • @using sandeepcodes.Models :- Here  we are giving path of Registration class, because registration class is inside of Model Folder & Sandeepcodes is my solution name .


Build your solution & Run the application.

Output  : -

Now How we will Select Records in MVC?? 

we will add one Edit link in Details page, Open Details.cshtml view page and write below code.

Add this code inside of For loop

                     <td>
                        @Html.ActionLink("EditData", "Edit", new { id = item.ID})
                    </td>



Complete view code are :

@using sandeepcodes.Models
    @{
        ViewBag.Title = "Details";
    }

    <h2>Details</h2>

    <div>
        <table class="table table-striped table-hover" style="width:800px; border:1px solid #cdcdcd">
            <tr>
                <td>Name</td>
                <td>MobileNo</td>
                <td>Address</td>
                <td>Age</td>
                <td>Email</td>
                <td></td>
            </tr>
             @foreach (RegistrationDetail item in Model)
             {
                <tr>
                    <td width="100px">@item.Name</td>
                    <td>@item.MobileNo</td>
                    <td>@item.Address</td>
                    <td>@item.Age</td>
                    <td>@item.EmailID</td>
                 
                    <td>

                        @Html.ActionLink("EditData", "Edit", new { id = item.ID})
                    </td>

                </tr>
             }


    </table>

</div>

Now we will add Action for Edit 

    public ActionResult Edit(int? id)
        { 
                RegistrationDetail empdetails = db.RegistrationDetails.Find(id);        
                return View(empdetails);
           
        }


Now execute you Details.cshtml view page and click on any edit link,  Records will show you on Edit view page.



Now we are going to Update select Records in MVC


Add below action for this and here we will use Post method because we are going to update details means submit to data into database.

let's have a look

Namespace are  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using sandeepcodes.Models;//  Add ref of Model
using System.Data.Entity;

Action :- 

  [HttpPost]
        public ActionResult Edit(RegistrationDetail obj)
        {
            RegistrationDetail data = db.RegistrationDetails.Find(obj.ID);
            data.EmailID = obj.EmailID;
            data.MobileNo = obj.MobileNo;
            data.Address = obj.Address;
            data.Age = obj.Age;
            db.Entry(data).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Details");

        }

 Build your application and execute Details.cshtml view page and select any record and update them.

How to Delete Record in MVC ??
Add on Delete link in Details.cshtml view page like Edit Link

  @Html.ActionLink("Delete", "Delete", new { id = item.ID })

Action for Delete

 public ActionResult Delete(int id)
        {
            RegistrationDetail detail = db.RegistrationDetails.Find(id);
            db.RegistrationDetails.Remove(detail);
            db.SaveChanges();
            return RedirectToAction("Details");

        }

Build your application & execute Details.cshtml page

See below image before delete record




After delete record 


Now Complete Controller Code are  :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using sandeepcodes.Models;//  Add ref of Model

using System.Data.Entity;

namespace sandeepcodes.Controllers
{
    public class RegistrationController : Controller
    {

        dataEntities db = new dataEntities(); // Create Connection


        // GET: Registration
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Insert()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Insert(RegistrationDetail obj)
        {
   
                db.RegistrationDetails.Add(obj);
                db.SaveChanges();  
                return RedirectToAction("Insert", "Registration");
        }

        public ActionResult Details()
        {
            var list = db.RegistrationDetails.ToList();
            return View(list);
        }


        public ActionResult Edit(int? id)
        { 
                RegistrationDetail empdetails = db.RegistrationDetails.Find(id);        
                return View(empdetails);
           
        }

        [HttpPost]
        public ActionResult Edit(RegistrationDetail obj)
        {
            RegistrationDetail data = db.RegistrationDetails.Find(obj.ID);
            data.Name = obj.Name;
            data.EmailID = obj.EmailID;
            data.MobileNo = obj.MobileNo;
            data.Address = obj.Address;
            data.Age = obj.Age;
            db.Entry(data).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Details");

        }

        public ActionResult Delete(int id)
        {
            RegistrationDetail detail = db.RegistrationDetails.Find(id);
            db.RegistrationDetails.Remove(detail);
            db.SaveChanges();
            return RedirectToAction("Details");
        }

    }


}

All operation has been completed, hope you will be enjoy it.

Give your feedback to improve the article.

No comments:

Post a Comment