Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconBig Databreadcumb forward arrow iconCRUD Operation in MVC

CRUD Operation in MVC

Last updated:
21st Feb, 2021
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
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.

Ads of upGrad blog

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”); 

Ads of upGrad blog

}

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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Popular Big Data Course

Frequently Asked Questions (FAQs)

1Why 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.

2Why 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.

3What 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.

Explore Free Courses

Suggested Blogs

13 Ultimate Big Data Project Ideas & Topics for Beginners [2023]
91053
Big Data Project Ideas Big Data is an exciting subject. It helps you find patterns and results you wouldn’t have noticed otherwise. This skill
Read More

by upGrad

07 Sep 2023

Big Data Architects Salary in India: For Freshers & Experienced [2023]
898874
Big Data – the name indicates voluminous data, which can be both structured and unstructured. Many companies collect, curate, and store data, but how
Read More

by Rohit Sharma

04 Sep 2023

12 Exciting Spark Project Ideas & Topics For Beginners [2023]
28969
What is Spark? Spark is an essential instrument in advanced analytics as it can swiftly handle all sorts of data, independent of quantity or complexi
Read More

by Rohit Sharma

29 Aug 2023

35 Must Know Big Data Interview Questions and Answers 2023: For Freshers & Experienced
1997
Introduction The demand for potential candidates is increasing rapidly in the big data technologies field. There are plenty of opportunities in this
Read More

by Mohit Soni

29 Aug 2023

Top 5 Big Data Use Cases in Healthcare
5829
Thanks to improved healthcare services, today, the average human lifespan has increased to a great extent. While this is a commendable milestone for h
Read More

by upGrad

28 Aug 2023

Big Data Career Opportunities: Ultimate Guide [2023]
5275
Big data is the term used for the data, which is either too big, changes with a speed that is hard to keep track of, or the nature of which is just to
Read More

by Rohit Sharma

22 Aug 2023

Apache Spark Dataframes: Features, RDD & Comparison
5334
Have you ever wondered about the concept behind spark dataframes? The spark dataframes are the extension version of the Resilient Distributed Dataset,
Read More

by Rohit Sharma

21 Aug 2023

Big Data Tutorial for Beginners: All You Need to Know
8294
Big Data, as a concept, has been evoked in almost every conversation about digital innovations, the Internet of Things (IoT), and data science researc
Read More

by Mohit Soni

28 Jun 2023

Cassandra Vs Hadoop: Difference Between Cassandra and Hadoop
5590
Big Data is thriving, and so are the technologies associated with it. Cassandra and Hadoop are a few of the popular technologies, which are used for,
Read More

by Rohan Vats

28 Jun 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon