ASP.NET Crud MVC: An Ultimate Guide With Examples

For several decades, the Model-View-Controller (MVC) design pattern has been extensively used across various technologies. This design pattern has been used in everything, including Smalltalk to C++, Java, C Sharp, and .NET Web applications benefit greatly from this powerful and straightforward method of decoupling issues within the application.

In this 'ASP.NET Crud MVC tutorial, you will learn the major technical aspects of the Model-View-Controller pattern and fundamentals involving views and Controllers.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Is ASP.NET MVC?

Microsoft's ASP.NET MVC is available as free and open-source software. Web development framework blends MVC (Model-View-Controller) structure, Iterative development approaches, and the best components of the current ASP.NET framework into a single, integrated platform.

As ASP.NET MVC is built on top of ASP.NET Framework, most ASP.NET capabilities are available to developers while creating MVC applications.

We can now go on to the next chapter to learn why we need ASP.NET MVC now that we have a basic knowledge of the definition and ASP.NET MVC.

Why Do We Need ASP.NET MVC?

When using ASP.NET MVC to create a web application, you won't have to worry about page load times or lifecycles. ASP.NET MVC also intends to be expandable throughout the whole framework as part of its architecture. As a result, we must use a certain sort of view engine when discussing views. 

The MVC framework has a feature that will create your controllers for us. If we don't like how they handle things, one can write their code for that reason. When you implement the Model-View-Controller paradigm, your objective is to create a clear division of work. It's the first time you may test your controller without tying it to the ASP.NET runtime or the ASPX web page.

Now that we understand the need for ASP.NET MVC let's try to implement CRUD operation in ASP.NET MVC.

Implementation of CRUD Operation in ASP.NET MVC Project

Let's start with creating an ASP.NET MVC Project. 

ASP.NET-MVC-Implementation-img1

Let's open visual studio 2019, click on a new project, and select Asp.Net Web Application.

ASP.NET-MVC-Implementation-img2

Then, we will name the project "MVCCrud" , select the location, and choose the .NET framework as ".NET Framework 4.7.2 ." Then we will hit the create button.

ASP.NET-MVC-Implementation-img3.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Next, we will be offered to choose the template, and we will choose MVC and hit create.

ASP.NET-MVC-Implementation-img4

We will delete the views part of the code from the default HomeController.cs file because we will create our files for that.

ASP.NET-MVC-Implementation-img5.

Now we will create a database first. So let's open server explorer and click on connect to database.

ASP.NET-MVC-Implementation-img6.

Now we will enter the server name as "(LocalDB)\MSSQLLocalDB" and the database name as "SimpliMVCDB." And then we will click ok.

ASP.NET-MVC-Implementation-img7

Then we will get a popup prompt asking us to create a new database with the proposed name above. So we will click yes.

Then we will explore this new database, right-click on the table, and select the new table.

ASP.NET-MVC-Implementation-img8

Then we will create the above table by filling up the cells, or you can paste the below queries into the query sheet.

Query:

CREATE TABLE Student

(

[StudentId] INT NOT NULL PRIMARY KEY, 

    [StudentName] NVARCHAR(50) NULL, 

    [StudentFees] INT NULL, 

    [StudentCity] NVARCHAR(50) NULL

)

ASP.NET-MVC-Implementation-img9.

Next, we will add and install a Nuget Package to our project, so we will open the manage Nuget package window, browse the tab, and search for EntityFramework. We will install the 5.0.0 version.

And then, we will click the update DataBase button to update the database.

ASP.NET-MVC-Implementation-img10.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Now we would include the ADO.Net Entity Data Model in our project. To add an ADO.Net Entity Data Model, click on our project name -> Add -> New Item.

ASP.NET-MVC-Implementation-img11.

We will select ADO.Net Entity Data Model, name it MVCModel, and hit add.

ASP.NET-MVC-Implementation-img12

Then we will select "EF Designer from DataBase" and hit Next.

ASP.NET-MVC-Implementation-img13

Then we will choose the database name and then make sure to check the "Save Connection setting in web. config". And then, we will name the connection name "SimpliMVCDBContext." 

ASP.NET-MVC-Implementation-img14

Then we will select Entity framework 5.0 And hit next. 

ASP.NET-MVC-Implementation-img15.

Now we will check the table option and hit Finish.

ASP.NET-MVC-Implementation-img16

Now you can check the project files. You may notice some new files are created.

Here is the code automatically created in the student.cs file. This code is created according to the table.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Code:

namespace MVCCrud

{

    using System;

    using System.Collections.Generic;   
    
    public partial class Student

    {

        public int StudentId { get; set; }

        public string StudentName { get; set; }

        public Nullable<int> StudentFees { get; set; }

        public string StudentCity { get; set; }

    }

}

ASP.NET-MVC-Implementation-img17.

Now create a view by right-clicking on the method and selecting Add View. A new popup window will appear with the following choices. Then press the Add button.

Now it automatically generates a view file "Index. cs" with the following code:

Code: 

@model IEnumerable<MVCCrud.Student>

@{

    ViewBag.Title = "Index";

}

<h2>Index</h2>

<p>

    @Html.ActionLink("Create New", "Create")

</p>

<table class="table">

    <tr>

        <th>

            @Html.DisplayNameFor(model => model.StudentName)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.StudentFees)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.StudentCity)

        </th>

        <th></th>

    </tr>

@foreach (var item in Model) {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.StudentName)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.StudentFees)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.StudentCity)

        </td>

        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |

            @Html.ActionLink("Details", "Details", new { id=item.StudentId }) |

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

        </td>

    </tr>

}

</table>

ASP.NET-MVC-Implementation-img18.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Now we will add a view to the creating method. It will create a new view with the code below

Code:

@model MVCCrud.Student

@{

    ViewBag.Title = "Create";

}

<h2>Create</h2>

@using (Html.BeginForm()) 

{

    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <h4>Student</h4>

        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">

            @Html.LabelFor(model => model.StudentId, htmlAttributes: new { @class = "control-label col-md-2" })

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

                @Html.EditorFor(model => model.StudentId, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.StudentId, "", new { @class = "text-danger" })

            </div>

        </div>

        <div class="form-group">

            @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })

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

                @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })

            </div>

        </div>

        <div class="form-group">

            @Html.LabelFor(model => model.StudentFees, htmlAttributes: new { @class = "control-label col-md-2" })

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

                @Html.EditorFor(model => model.StudentFees, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.StudentFees, "", new { @class = "text-danger" })

            </div>

        </div>

        <div class="form-group">

            @Html.LabelFor(model => model.StudentCity, htmlAttributes: new { @class = "control-label col-md-2" })

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

                @Html.EditorFor(model => model.StudentCity, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.StudentCity, "", new { @class = "text-danger" })

            </div>

        </div>

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <input type="submit" value="Create" class="btn btn-default" />

            </div>

        </div>

    </div>

}

<div>

    @Html.ActionLink("Back to List", "Index")

</div>

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")

}

Now we will add edit methods in the controller file. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Code:

[HttpGet]  

public ActionResult Edit(int id)  

{               

    var data = _context.Employees.Where(x => x.EmployeeId == id).FirstOrDefault();  

    return View(data);  

}  

[HttpPost]  

public ActionResult Edit(Employee Model)  

{  

    var data = _context.Employees.Where(x => x.EmployeeId == Model.EmployeeId).FirstOrDefault();  

    if (data != null)  

    {
  
        data.EmployeeCity = Model.EmployeeCity;  

        data.EmployeeName = Model.EmployeeName;  

        data.EmployeeSalary = Model.EmployeeSalary;  

        _context.SaveChanges();  

    }
  
    return RedirectToAction("index");  

} 

ASP.NET-MVC-Implementation-img19

Now let's add an edit view for the edit method. It will create an edit view file and automatically have the code below.

Code:

@model MVCCrud.Student
@{
    ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()    
    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.StudentId)
        <div class="form-group">
            @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.StudentFees, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentFees, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentFees, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.StudentCity, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentCity, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentCity, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Now let's write a detailed method to display employee information.

Code:

public ActionResult Detail(int id)

        {

            var data = _context.Students.Where(x => x.StudentId == id).FirstOrDefault();

            return View(data);

        }

ASP.NET-MVC-Implementation-img20.

Now we'll develop a view for displaying employee information. As a result, add a parameter id to the Action method description. We fetch data from the database and feed it to the view.

Code:

@model MVCCrud.Student

@{

    ViewBag.Title = "Detail";

}

<h2>Detail</h2>

<div>

    <h4>Student</h4>

    <hr />

    <dl class="dl-horizontal">

        <dt>

            @Html.DisplayNameFor(model => model.StudentName)

        </dt>

        <dd>

            @Html.DisplayFor(model => model.StudentName)

        </dd>

        <dt>

            @Html.DisplayNameFor(model => model.StudentFees)

        </dt>

        <dd>

            @Html.DisplayFor(model => model.StudentFees)

        </dd>

        <dt>

            @Html.DisplayNameFor(model => model.StudentCity)

        </dt>

        <dd>

            @Html.DisplayFor(model => model.StudentCity)

        </dd>

    </dl>

</div>

<p>

    @Html.ActionLink("Edit", "Edit", new { id = Model.StudentId }) |

    @Html.ActionLink("Back to List", "Index")

</p>

Now we develop a delete Action Method using id as the n argument.

Code: 

public ActionResult Delete(int id)

        {

            var data = _context.Student.Where(x => x.StudentId == id).FirstOrDefault();

            _context.Student.Remove(data);

            _context.SaveChanges();

            ViewBag.Messsage = "Record Delete Successfully";

            return RedirectToAction("index");

        }

ASP.NET-MVC-Implementation-img21.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Now we will right-click the delete method and add a delete view. And it will create a delete view. And here is the code for it.

Code:

@model MVCCrud.Student
@{
    ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Student</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.StudentName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.StudentName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.StudentFees)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.StudentFees)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.StudentCity)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.StudentCity)
        </dd>
    </dl>
    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }
</div>

And with this, we are done with all the files. Let's have a look at the final controller code.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCCrud.Controllers
{
    public class HomeController: Controller
    {
        SimpliMVCDBContext _context = new SimpliMVCDBContext();
        public ActionResult Index()
        {
            var listofData = _context.Students.ToList();
            return View(listofData);
        }
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Student model)
        {
            _context.Students.Add(model);
            _context.SaveChanges();
            ViewBag.Message = "Data Insert Successfully";
            return View();
        }
        [HttpGet]
        public ActionResult Edit(int id)
        {
            var data = _context.Students.Where(x => x.StudentId == id).FirstOrDefault();
            return View(data);
        }
        [HttpPost]
        public ActionResult Edit(Student Model)
        {
            var data = _context.Students.Where(x => x.StudentId == Model.StudentId).FirstOrDefault();
            if (data != null)
            {
                data.StudentCity = Model.StudentCity;
                data.StudentName = Model.StudentName;
                data.StudentFees = Model.StudentFees;
                _context.SaveChanges();
            }
            return RedirectToAction("index");
        }
        public ActionResult Detail(int id)
        {
            var data = _context.Students.Where(x => x.StudentId == id).FirstOrDefault();
            return View(data);
        }
        public ActionResult Delete(int id)
        {
            var data = _context.Students.Where(x => x.StudentId == id).FirstOrDefault();
            _context.Students.Remove(data);
            _context.SaveChanges();
            ViewBag.Messsage = "Record Delete Successfully";
            return RedirectToAction("index");
        }
    }
}

Now let's try to run it.

ASP.NET-MVC-Implementation-img22

Here is the base website.

ASP.NET-MVC-Implementation-img23

Now let's click create new. And it will open a new form.

ASP.NET-MVC-Implementation-img24.

Now when we click create. And it will create the above field.

You can try other functions for the said functions.

Now that we have successfully implemented the CRUD Operations. Let's glance over a few benefits of ASP.NET MVC.

Benefits of ASP.NET MVC

There are many benefits of ASP.NET MVC.

  • ASP.NET MVC makes it easier to make current projects more interactive and responsive.
  • ASP.NET MVC provides clear segregation of responsibilities and gives you complete command over the rendered HTML.
  • Direct control over HTML also implies improved accessibility when adhering to changing Web standards.
  • Large teams of developers can benefit from using ASP.NET MVC and web designers that need a lot of control over the application's behavior.
  • ASP.NET MVC simplifies complexity management by splitting an application into the model, the view, and the controller.
  • Test-driven development (TDD) is made easier using ASP.NET MVC.

By now, you have a good grip on the technical and theoretical aspects of ASP.NET MVC. 

Next Steps

The next lesson in your C# training can be "ASP.NET SQL Connection." A SqlConnection object represents a single SQL Server data source session. A client/server database system is comparable to a network connection to the server. A SqlConnection object uses Connectionstring, which Gets or Sets the string needed to open a SQL Server database. To open and close a SQL Connection, use connection.open() and connection.close().

Simplilearn is the world's most popular online Bootcamp for learning digital economy skills, and it's here to help you do that. Digital marketing and data science are just a few subjects we cover in-depth in our online courses.

You've come to the right place if you're interested in learning more about software development and working in the field. The Caltech CTME and the Indian Institute of Technology, Kanpur, have collaborated with Simplilearn to deliver their Post Graduate Program in Full Stack Web Development courses\. In addition to more advanced topics like Competitive Programming, these courses teach the fundamentals of data structures and algorithms. As a software developer, data structures, including trees, graphs, and queues, will be taught to you.

The comments section below is open for questions and comments about this "ASP.NET Crud MVC" tutorial. Happy learning!

About the Author

Vaibhav KhandelwalVaibhav Khandelwal

Vaibhav Khandelwal is a proactive tech geek who's always on the edge of learning new technologies. He is well versed in competitive programming and possesses sound knowledge of web development. He likes to read fictional and sci-fi novels and likes to play strategy games like chess

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.