MVC CRUD Operation - With Example

MVC CRUD Operation:

CRUD operation is nothing but to perform (CREATE, RETRIEVE, UPDATE and DELETE) records (collections of data) using the database. Here I Explained how to perform CRUD operation in ASP.NET MVC using EF (Entity-Framework) with Examples.

What is Entity-Framework?

  • Entity Framework is an ORM framework.
  • ORM stands for Object Relational Mapping.
  • Object Relational Mapping framework automatically creates classes based on database tables, and the vice versa is also true, that is, it can also automatically generate the necessary SQL to create database tables based on classes.

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 step by step using images. 

Step 1: Open Project

  • Open Visual Studio.
  •  Go to File, New Menu and select "Project..." or "ctrl + shift + n".
  • In the "New Project" dialog, select "Templates", Visual C#,  then Web and select "ASP.NET Web Application". After that provide the name you want to save and click "OK".
  • In the next screen select ASP.NET Template as "MVC" as shown in the following screen. This screen also offers to include "core references" for Web Forms and Web API as well. If you want you can just add those by checking the checkbox. If you also want to add "Unit Tests" for this project, Visual Studio will add one for you, if you check "Add unit tests" checkbox. Click "OK" to open the selected template.
  • That's it. You have successfully created an ASP.NET MVC Web Project. It will look like below, as you can see, it will consist of all the necessary files to start the development. You can see this in the solution explorer.

Step 2: Creating a database

Right  Click a Project Solution  >> Click Add  >>  Click Add New Item >> Click SQL Server Database (you can name it as whatever valid name you want).



Right-clicking a Table Folder  >>  add the new table


Step 3: Creating an Entity Framework

Right  Click a Project Solution  >> Click Add  >>  Click Add New Item >> Click ADO.NET Entity Data Model (you can name it as whatever valid name you want).


Then select an EF Designer from database >> Click NEXT


Then choose your data connection by clicking your database name in the dropdown and add your connection string name.


Here you should add table or view or stored procedure by clicking the checkbox and add model namespace name then click next.


Here you successfully created an entity framework and also you can view the structure of the table.


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

NoteBefore proceeding to Step 4, build the project. It's recommended.

Step 4: Add  the Controller

By clicking a controller folder >> then select controller and add a name for it.



Add this c# code in your controller to perform CRUD operation


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SampleCrudOperation.Models;
using System.Data.Entity;

namespace SampleCrudOperation.Controllers
{
    public class RegisterController : Controller
    {
        public ActionResult Index()
        {
            //Creating a instance for our model
            RegisterDetails myModel = new RegisterDetails();
            return View(myModel);
        }

        [HttpPost]
        public ActionResult Index(RegisterDetails myModel)
        {
            //TempData is used to passing the data from controller to view
            TempData["Message"] = "There is a problem while creating data";
            //checking null value
            if (myModel != null)
            {
                //Creating a instance for db model 
                Reg_Details dbModel = new Reg_Details();
                dbModel.Name = myModel.Username;
                dbModel.Age = myModel.Age;
                dbModel.City = myModel.City;
                //Declaring EF class to access DB
                using (var _db = new MyDbEntities())
                {
                    _db.Reg_Details.Add(dbModel);
                    _db.SaveChanges();
                    TempData["Message"] = "Created Successfully!!!";
                }
            }
            return View();
        }

        public ActionResult Details()
        {
            //Declaring EF class to access DB
            using (var _db = new MyDbEntities())
            {
                var dbList = _db.Reg_Details.ToList();
                List<Reg_Details> myList = new List<Reg_Details>(dbList);
                //checking null value
                if (myList != null && myList.Any())
                {
                    return View(myList);
                }
            }
            return RedirectToAction("Index");
        }

        public ActionResult Delete(int userId)
        {
            Reg_Details dbModel = new Reg_Details();
            if (userId > 0)
            {
                using (var entities = new MyDbEntities())
                {
                    dbModel = entities.Reg_Details.Find(userId);
                }
            }
            return View(dbModel);
        }

        [ActionName("Delete")]
        [HttpPost]
        public ActionResult DeleteConfirmed(int? Id)
        {
            TempData["DeleteMessage"] = "There is a problem while deleting data";
            //checking null value for user id
            if (Id > 0)
            {
                using (var entities = new MyDbEntities())
                {
                    var dataToDelete = entities.Reg_Details.Where(m => m.Id == Id).SingleOrDefault();
                    if (dataToDelete != null)
                    {
                        entities.Reg_Details.Remove(dataToDelete);
                        entities.SaveChanges();
                    }
                }
                TempData["DeleteMessage"] = "Deleted Successfully!!!";
            }
            return View();
        }

        public ActionResult Update(int userId)
        {
            Reg_Details dbModel = new Reg_Details();
            if (userId > 0)
            {
                using (var entities = new MyDbEntities())
                {
                    dbModel = entities.Reg_Details.Find(userId);
                }
            }
            return View(dbModel);
        }

        [ActionName("Update")]
        [HttpPost]
        public ActionResult UpdateUser(Reg_Details myModel)
        {
            TempData["UpdateMessage"] = "There is a problem while updating data";
            //checking null value for user id
            if (myModel !=null)
            {
                using (var entities = new MyDbEntities())
                {
                        //add namespace for entity state
                        entities.Entry(myModel).State = EntityState.Modified;
                        entities.SaveChanges();
                }
                TempData["UpdateMessage"] = "Updated Successfully!!!";
            }
            return View();
        }

    }
}

Step 5: Add the Model

By clicking a Model folder >> then select Class and add a name for it.



Add this code in your Model

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

namespace SampleCrudOperation.Models
{
    public class RegisterDetails
    {
        public int UserId { get; set; }
        public string Username { get; set; }
        public int Age { get; set; }
        public string City { get; set; }
    }
}

Step 6: CRUD using Entity Framework

By clicking a View folder >> then select View and add a name for it.


To perform CRUD we need to add Four view page I have mentioned below:
  • Index.cshtml
  • Details.cshtml
  • Update.cshtml
  • Delete.cshtml
Note: If you want to add layout, Then choose the use a layout checkbox to add with a layout.


Add this code in Index.cshtml

@model SampleCrudOperation.Models.RegisterDetails
@{
    ViewBag.Title = "Register Page";
}
<center>
    <div style="text-align:left;font-size:20px;">
        @Html.ActionLink("Click here to view user details", "Details")
    </div>
    @using (Html.BeginForm("Index", "Register", FormMethod.Post))
    {
        <h2>Register Form</h2>
        <table>
            <tr>
                <td>Name:</td>
                <td>@Html.TextBoxFor(m => m.Username)</td>
            </tr>
           
            <tr>
                <td>Age:</td>
                <td>@Html.TextBoxFor(m => m.Age)</td>
            </tr>
            
            <tr>
                <td>City:</td>
                <td>@Html.TextBoxFor(m => m.City)</td>
            </tr>
        </table>
        <br />
        <input type="submit" value="Create" /><br />
        <h3>@TempData["Message"]</h3>
    }
</center>
Add this code in Details.cshtml

@model List<SampleCrudOperation.Reg_Details>
@{
    ViewBag.Title = "User Details";
}
<center>
    <h2>User Details</h2>
    <table border="1">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
            <th>City</th>
            <th></th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Id</td>
                <td>@item.Name</td>
                <td>@item.Age</td>
                <td>@item.City</td>
                <td>@Html.ActionLink("Delete","Delete",new { userId=item.Id}) | @Html.ActionLink("Update", "Update", new { userId = item.Id })</td>
            </tr>
        }
        
    </table>
</center>

Add this code in Update.cshtml
@model SampleCrudOperation.Reg_Details
@{
    ViewBag.Title = "Update User Details";
}
<center>
    <h2>@TempData["UpdateMessage"]</h2>
    @using (Html.BeginForm("Update", "Register", FormMethod.Post))
    {
        <table border="1">
            <thead>
                <tr>
                    <td>Id:</td>
                    <td>Name:</td>
                    <td>Age:</td>
                    <td>City:</td>
                </tr>
            </thead>
            <tr>
                <td>@Html.DisplayFor(m => m.Id)</td>
                <td>@Html.TextBoxFor(m => m.Name)</td>
                <td>@Html.TextBoxFor(m => m.Age)</td>
                <td>@Html.TextBoxFor(m => m.City)</td>
            </tr>
        </table>
        //User this for to get id value in post method because @html.displayfor not used for post method
        @Html.HiddenFor(m => m.Id)
        <input type="submit" value="Click here to Update" />
    }
    <br /><br />
    @Html.ActionLink("Back to Details", "Details")
</center>


Add this code in Delete.cshtml
@model SampleCrudOperation.Reg_Details
@{
    ViewBag.Title = "Delete User Details";
}
<center>
    <h2>@TempData["DeleteMessage"]</h2>
    @using (Html.BeginForm("Delete", "Register", FormMethod.Post))
    {
        <table border="1">
            <thead>
                <tr>
                    <td>Id:</td>
                    <td>Name:</td>
                    <td>Age:</td>
                    <td>City:</td>
                </tr>
            </thead>
            <tr>
                <td>@Html.DisplayFor(m => m.Id)</td>
                <td>@Html.DisplayFor(m => m.Name)</td>
                <td>@Html.DisplayFor(m => m.Age)</td>
                <td>@Html.DisplayFor(m => m.City)</td>
            </tr>
        </table>
        <br />
        //User this for to get value in post method
        @Html.HiddenFor(m => m.Id)
        <input type="submit" value="Are you sure you want to delete this data?" />
    }
    <br /><br />
    @Html.ActionLink("Back to Details", "Details")
</center>


Step 6: Configure a route config file in App_Start Folder



The route is configured using the MapRoute() extension method of RouteCollection, 
where name is "Default", url pattern is "{controller}/{action}/{id}" and defaults parameter for controller, action method and id parameter.
 Defaults specifies which controller, action method or value of id parameter should be used if they do not exist in the incoming request URL.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace SampleCrudOperation
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Register", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Output:


Just run that page and you will see a page like this. This is your default page of CRUD operations. You can access all the other options.






Right-click the table >> select show table data

Here you can view the data store in DB

Conclusion:

Congrats guys!

  • Just clap for yourself, because you have done a great job. You performed CRUD operations using ASP.NET MVC.
  • I wish you liked this, I'll come with some other exciting parts of MVC operations soon, until then enjoy coding and if you encounter any problem then feel free to ping me.

Comments

Post a Comment

Popular posts from this blog

Send Mail with Attachment using MVC

ASP.Net MVC: ViewData, ViewBag and TempData with examples

Difference Between Web Services, WCF and WEB API