Programs

CRUD Operation in MVC

Introduction

CRUD operation in MVC is the basic operations, where CRUD denotes create, read, update, and delete. But before understanding the basic operations of MVC, first, learn about MVC. MVC is the Model View Controller. MVC is a design pattern that is used to differentiate the data from business logic and presentation logic. It gives a pattern that helps in designing the web application.

Check out our free courses to get an edge over the competition.

MVC divides the application into three layers, as described below:

1. Model Layer: MVC has a model component that deals with logic-related data. The model layer represents the information transferred between view and controller layers of data related to the business logic. For example, employee objects help fetch the employee information from the relevant table in the database, manipulate the data, and then update it back into the database.

2. View Layer: The view layer has the view components that deal with the User interface logic. As an illustration, an employee’s view components comprise the components, such as text boxes, radio buttons, drop-downs, check-boxes, etc. The view layer has the components that the end-user deals with.

3. Controller Layer: Controller is the interface between view layer components and model layer components. The controller controls the business logic. It receives the user input through the view layer and processes the information through the model layer. 

The processed information is then returned to the user by the controller through the view layer. 

To exemplify, an employee wants to see the salary-related information. The employee can enter the details through UI components in view; the controller then retrieves the relevant information from the model layer and displays the information to the employee’s view layer to see it.

The interaction between the MVC layers can be easily understood using the below diagram:

 These were the basics of MVC. Now, coming back to our original topic, the basic CRUD operation in MVC. Below are the CRUD operations:

  • Create a record in the database
  • Read a record in the database
  • Update a record in the database
  • Delete a record in the database

Explore Our Software Development Free Courses

Steps to Create an MVC Project

1. First, create an MVC application. Click on Start on your PC, and then click on All Programs.

2. Click on Microsoft Visual Studio 2015.

3. Click on File > New > Project and select ASP.NET Web Application Template.

4. Enter the project name and click Ok.

5. Click on Empty, check the check-box MVC, and click on Ok. An empty MVC web application will open.

6. Right-click on the Models folder, then add the option, and then the class option.

Below is the code snippet for the class called Employee1.cs:

public class Employee1 

  { 

   [Display(Name = “EmpId”)] 

   public int Empid { get; set; }  

   [Required(ErrorMessage = “First name is required.”)] 

   public string FName { get; set; } 

   [Required(ErrorMessage = “City is required.”)] 

   public string City { get; set; } 

   [Required(ErrorMessage = “Address is required.”)] 

   public string Address { get; set; } 

  }

7. The next step is adding a controller. Select MVC5 Controller with read/write a class and click on the Add button. Enter the controller name.

Explore our Popular Software Engineering Courses

CRUD Operation in MVC

1. Create a Record in the Database

Create a new record in the new controller using the below code snippet: 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace CRUDDemo.Controllers

{

    public class CRUDController : Controller

    {

        // To create View of this Action result

        public ActionResult create() 

        {

            return View();

        }

        // Specify the type of attribute i.e.

        // it will add the record to the database

        [HttpPost] 

        public ActionResult create(Employee1 emp)

        {

                     If (ModelState.IsValid)

                     {

                                 Db.Employee1.Add(emp);

                                 Db.SaveChanges();

                                 Return RedirectToAction(“Index”);

                     }

                     Return View(emp);

         }              

}

2. Read the Record From the Database

Below is the code to read the record from the database

public ActionResult Read()

{

using(var context = new demoCRUDEntities())

{

// Return the data from database

var data = context.Employee1.ToList(); 

return View(data);

}

}

Read: Exception Handling in MVC

3. Update a Record in the Database

Below is the code to edit or update the record in the database:

public ActionResult Edit(string id = null) 

Employee1 emp = db.Employee1.Find(id); 

if (emp == null) 

return HttpNotFound(); 

return View(emp); 

}   

 [HttpPost] 

public ActionResult Edit(Employee1 emp) 

if (ModelState.IsValid) 

db.Entry(emp).State = EntityState.Modified; 

db.SaveChanges(); 

return RedirectToAction(“Index”); 

return View(emp); 

}

In-Demand Software Development Skills

4. Delete the Record From the Database

Below is the code snippet to delete the record from the database:

public ActionResult Delete(string id = null) 

{

Employee1emp = db.Employee1.Find(id); 

if (emp == null) 

return HttpNotFound(); 

return View(emp); 

}    

[HttpPost, ActionName(“Delete”)] 

[ValidateAntiForgeryToken] 

public ActionResult DeleteConfirmed(string id) 

Employee1 emp = db.Employee1.Find(id); 

db.Employee1.Remove(emp); 

db.SaveChanges(); 

return RedirectToAction(“Index”); 

}

Read our Popular Articles related to Software Development

Conclusion

CRUD is the most basic operations of MVC used in ASP.net. I hope the CRUD operation in MVC is clear to you now, and you can try implementing this code to perform the CRUD operations.  

If you are interested to know more about Big Data, check out our Advanced Certificate Programme in Big Data from IIIT Bangalore.

Check our other Software Engineering Courses at upGrad.

Why is CRUD important?

The ability to create, read, update, and delete items in a web application is crucial to most projects. For example, if you are creating a blog posting page or to-do list or social media clone, without CRUD actions will get stuck very quickly. CRUD is too important to be ignored. Hence, learning it can really improve your confidence within unfamiliar stacks. Without CRUD operations, software developers can’t get anything done. End-users also heavily rely on CRUD. One can easily add or create new entries, search for and update existing ones, and delete them in most of the applications using CRUD. It simplifies security control, makes application design easier, and helps scale the system by simplifying and facilitating it.

Why do we use MVC?

Model View Controller is a methodology or architectural pattern used for efficiently relating the user interface to underlying data models and organising to relate the application code. There are various benefits of using MVC. It organises large size web applications. As there is segregation of the code among the three levels, it becomes easy to divide and organise web application logic into large-scale applications. MVC methodology also allows easy modification of the entire application, allows easy implementation of business logic, and helps accelerate the development process.

What are the benefits of acquiring an MVC certification in 2022?

MVC is a technology that provides you with a series of benefits. While working with the MVC framework, you will get the opportunity of creating a web application. You will also find MVC architecture working substantially in tune with the JavaScript frameworks indicating that you could run MVC apps without problems anywhere. The framework helps you in accelerating the whole work process. MVC is a course worth learning, and it has a bright future ahead as well. There are several companies looking for skilled MVC professionals, which has increased the benefits of acquiring an MVC certification.

Want to share this article?

Lead the Data Driven Technological Revolution

400+ HOURS OF LEARNING. 14 LANGUAGES & TOOLS. IIIT-B ALUMNI STATUS.
Apply Now for Executive PG Program in Full Stack Development

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Big Data Course

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks