0% found this document useful (0 votes)
246 views26 pages

CRUD Operation in ASP

1. The document describes the steps to perform CRUD operations in ASP.NET MVC using Entity Framework. It involves creating a database and model class, scaffolding the controller and views, and adding methods for each CRUD operation. 2. Key steps include installing Entity Framework, generating an Entity Data Model from an existing database, adding controller actions and views for each operation (index, create, edit, delete), and using Entity Framework methods like Add, SaveChanges to insert, update, and delete database records. 3. Example code is provided for the Index, Create, and Edit controller actions and views to demonstrate how each CRUD operation is implemented programmatically and through the UI.

Uploaded by

invtm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
246 views26 pages

CRUD Operation in ASP

1. The document describes the steps to perform CRUD operations in ASP.NET MVC using Entity Framework. It involves creating a database and model class, scaffolding the controller and views, and adding methods for each CRUD operation. 2. Key steps include installing Entity Framework, generating an Entity Data Model from an existing database, adding controller actions and views for each operation (index, create, edit, delete), and using Entity Framework methods like Add, SaveChanges to insert, update, and delete database records. 3. Example code is provided for the Index, Create, and Edit controller actions and views to demonstrate how each CRUD operation is implemented programmatically and through the UI.

Uploaded by

invtm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

CRUD Operation in ASP.

NET MVC
Sumukh J
Introduction
In this article I will explain how we can make CRUD operations in ASP.Net MVC. In
this article we will use a data base first approach and perform CRUD operations
using entity framework. I hope you like this article and get some information from it.

Step 1

Open Visual Studio. Here I use Visual Studio 2019, you can use any one as your
system.

Step 2

Create a new project by clicking on File>New>Project.

Step 3

Select Asp.Net Web Application and click on next button.


Step 4

In the next screen you need to enter a few details like your project name, project
location where you want to save your project, solution name, and .Net Framework
version. After entering all details click on Create button.
Step 5

In Next select MVC project and click on Create button.


Now your project is ready and you can see project structure in below image. Here I
deleted all view from home controller because we created a new for our
requirement.
Step 6

Now in this project we will use database first approach so we need to create a
database and a table. Here I created a database name with Tutorials and table
Employee with the following columns as you can see in the below image.

Step 7
Now we need to add Entity Framework in our project for performing some operation.
For adding Entity Framework click on project name in solution explore then click on
Manage NuGet Packages.

Step 8

Now you see a window with many NuGet Packages. Search for Entity framework
and click on install button and after a few seconds Entity Framework is installed in
your project.
Step 9

Now we need to add ADO.Net Entity Data Model in our project. For adding ADO.Net
Entity Data Model click on your project name then click on Add and then click on new
Item or you can use short cut key Ctrl+Shift+A .
Step 10

Now you see a popup window. Select ADO.Net Entity Data Model, give appropriate
name and click on add button.
Note
There is a change that in visual studio 2019 you cannot see ADO.Net Entity Data
Model option. For adding ADO.Net Entity Data Model in visual studio open visual
studio install , select modify option by clicking on more button. Now you see a new
window click on Individual Component tab, search for Entity Framework tool then
select it and click on modify button.
Now it starts downloading. If your visual studio is open then save all files because it
will close visual studio before installing updates.

Step 11

After adding ADO.Net Entity Data Model you will see a popup window. Select EF
Designer From database and click on next button.

Step 12

Now select your database from drop down and give connection string name,
and click on Next button.
Step 13

Select tables which you want to add in project, here I have only one table so I select
that, gave Model Namespace name and Click on finish button.
Now Entity Framework creates an edmx file in your project as you can see in the
below image.
Here is Employee Model.

1. public partial class Employee


2. {
3.
4. public int EmployeeId { get; set; }
5. public string EmployeeName { get; set; }
6. public Nullable<decimal> EmployeeSalary { get; set; }
7. public string EmployeeCity { get; set; }
8. }

Step 14

Now delete all method from your controller and add index method as show in the
below code.

1. public ActionResult Index()


2. {
3. var listofData = _context.Employees.ToList();
4. return View(listofData);
5. }

Step 15

Now add view by right clicking in method then click on Add View and you will see a
new popup window with the following options. And then click on Add button.

 View Name: Name of your Cs Html file


 Template: There are many templates which give pre defined design like list,
create, edit, delete, details select list for index method
 Model Class: Select your model class which we generated in the previous step.
 Data Context Class: Select your data context class, here I have TutorialCS
whose name we gave in previous step.
 Use Layout Page: if you check this item compiler add layout file from _Shared
folder in this view. You can select different layout file if you have more than one
.
Now Compiler generates view for list modifier design if you want. Design file code is
below.

1. @model IEnumerable<CrudOperationInMVC.Controllers.Employee>
2.
3. @{
4. ViewBag.Title = "Index";
5. }
6.
7. <div>Index</div>
8.
9. <p class="text-right">
10. @Html.ActionLink("Create New", "Create")
11. </p>
12.
13. @if (ViewBag.Message != null)
14. {
15.
16. <div class="alert alert-success" role="alert">
17. @ViewBag.Message
18. </div>
19. }
20.
21.
22. <table class="table">
23. <tr>
24. <th>
25. @Html.DisplayNameFor(model => model.EmployeeName)

26. </th>
27. <th>
28. @Html.DisplayNameFor(model => model.EmployeeSalary
)
29. </th>
30. <th>
31. @Html.DisplayNameFor(model => model.EmployeeCity)

32. </th>
33. <th></th>
34. </tr>
35.
36.
37. @if (Model != null && Model.Count() > 0)
38. {
39. foreach (var item in Model)
40. {
41. <tr>
42. <td>
43. @Html.DisplayFor(modelItem => item.Employe
eName)
44. </td>
45. <td>
46. @Html.DisplayFor(modelItem => item.Employe
eSalary)
47. </td>
48. <td>
49. @Html.DisplayFor(modelItem => item.Employe
eCity)
50. </td>
51. <td>
52. @Html.ActionLink("Edit", "Edit", new { id
= item.EmployeeId }) |
53. @Html.ActionLink("Details", "Detail", new
{ id = item.EmployeeId }) |
54. @Html.ActionLink("Delete", "Delete", new {
id = item.EmployeeId })
55. </td>
56. </tr>
57. }
58. }
59. else
60. {
61. <td colspan="4" class="text-
center"><b>No Data Available . Please Add Data By CLick On Creat
e Button</b></td>
62. }
63. </table>

Step 16

Now we create a view for adding a new record. Here we need to create two Action
methods, one is get method and the second is post method. Get method is called
when we click on create button and return view. Post method is used for saving data
in the table.

1. [HttpGet]
2. public ActionResult Create()
3. {
4. return View();
5. }
6.
7. [HttpPost]
8. public ActionResult Create(Employee model)
9. {
10. _context.Employees.Add(model);
11. _context.SaveChanges();
12. ViewBag.Message = "Data Insert Successfully";
13. return View();
14. }

Code Explanation
 In post method we pass Employee class as a parameter as model name which
gets all data from user.
 Then we add that model in TutoriaCS using _context object which we create top
of controller.
 SaveChanges() method use for save all changes which we make in entity like
add, delete, update etc.
 You can see output of create below.
For Adding view for Create right click in method click on add view and select
template Create.

Design for create view is below,

1. @model CrudOperationInMVC.Controllers.Employee
2.
3. @{
4. ViewBag.Title = "Create";
5. }
6.
7. <div>Create</div>
8.
9. @if (ViewBag.Message != null)
10. {
11. <div class="alert alert-success" role="alert">
12. @ViewBag.Message
13. </div>
14. }
15.
16.
17. @using (Html.BeginForm())
18. {
19. @Html.AntiForgeryToken()
20.
21. <div class="form-horizontal">
22. <div>Employee</div>
23. <hr />
24. @Html.ValidationSummary(true, "", new { @class = "text
-danger" })
25. <div class="form-group">
26. @Html.LabelFor(model => model.EmployeeName, htmlAt
tributes: new { @class = "control-label col-md-2" })
27. <div class="col-md-10">
28. @Html.EditorFor(model => model.EmployeeName, n
ew { htmlAttributes = new { @class = "form-control" } })
29. @Html.ValidationMessageFor(model => model.Empl
oyeeName, "", new { @class = "text-danger" })
30. </div>
31. </div>
32.
33. <div class="form-group">
34. @Html.LabelFor(model => model.EmployeeSalary, html
Attributes: new { @class = "control-label col-md-2" })
35. <div class="col-md-10">
36. @Html.EditorFor(model => model.EmployeeSalary,
new { htmlAttributes = new { @class = "form-control" } })
37. @Html.ValidationMessageFor(model => model.Empl
oyeeSalary, "", new { @class = "text-danger" })
38. </div>
39. </div>
40.
41. <div class="form-group">
42. @Html.LabelFor(model => model.EmployeeCity, htmlAt
tributes: new { @class = "control-label col-md-2" })
43. <div class="col-md-10">
44. @Html.EditorFor(model => model.EmployeeCity, n
ew { htmlAttributes = new { @class = "form-control" } })
45. @Html.ValidationMessageFor(model => model.Empl
oyeeCity, "", new { @class = "text-danger" })
46. </div>
47. </div>
48.
49. <div class="form-group">
50. <div class="col-md-offset-2 col-md-10">
51. <input type="submit" value="Create" class="btn
btn-default" />
52. </div>
53. </div>
54. </div>
55. }
56.
57. <div>
58. @Html.ActionLink("Back to List", "Index")
59. </div>
60.
61. @section Scripts {
62. @Scripts.Render("~/bundles/jqueryval")
63. }

Output

Step 17

Now we will implement Edit functionality. For edit we also create two methods, get
and post type. Get type method gets data from database by recording it and passing
it in view. Post method saves updated data in database. Code for both methods is
below.

1. [HttpGet]
2. public ActionResult Edit(int id)
3. {
4. var data = _context.Employees.Where(x => x.EmployeeId == id)
.FirstOrDefault();
5. return View(data);
6. }
7. [HttpPost]
8. public ActionResult Edit(Employee Model)
9. {
10. var data = _context.Employees.Where(x => x.EmployeeId == M
odel.EmployeeId).FirstOrDefault();
11. if (data != null)
12. {
13. data.EmployeeCity = Model.EmployeeCity;
14. data.EmployeeName = Model.EmployeeName;
15. data.EmployeeSalary = Model.EmployeeSalary;
16. _context.SaveChanges();
17. }
18.
19. return RedirectToAction("index");
20. }

Code Explanation
 In get type method we get an id as a parameter using that we get first record
from database and initialize in data variable then return that variable in view
 In post type method we get Employee type model as a parameter; we get
record from database with EmployeeId which comes with parameter.
 If record is found in database with that id then we initialize upcoming data in
database data.
 And save changes using SaveChanges Method. And return to index method
using RedirectToAction method.
Step 18

Now we need to add view for editing. For this right click in Edit method click on Add
View and select Edit Template' all other options are the same as index.

Code of View for Edit is below.

1. @model CrudOperationInMVC.Controllers.Employee
2.
3. @{
4. ViewBag.Title = "Edit";
5. }
6.
7. <div>Edit</div>
8.
9.
10.
11. @if (ViewBag.Message != null)
12. {
13.
14. <div class="alert alert-success" role="alert">
15. @ViewBag.Message
16. </div>
17. }
18.
19.
20. @using (Html.BeginForm())
21. {
22. @Html.AntiForgeryToken()
23.
24. <div class="form-horizontal">
25. <div>Employee</div>
26. <hr />
27. @Html.ValidationSummary(true, "", new { @class = "text
-danger" })
28. @Html.HiddenFor(model => model.EmployeeId)
29.
30. <div class="form-group">
31. @Html.LabelFor(model => model.EmployeeName, htmlAt
tributes: new { @class = "control-label col-md-2" })
32. <div class="col-md-10">
33. @Html.EditorFor(model => model.EmployeeName, n
ew { htmlAttributes = new { @class = "form-control" } })
34. @Html.ValidationMessageFor(model => model.Empl
oyeeName, "", new { @class = "text-danger" })
35. </div>
36. </div>
37.
38. <div class="form-group">
39. @Html.LabelFor(model => model.EmployeeSalary, html
Attributes: new { @class = "control-label col-md-2" })
40. <div class="col-md-10">
41. @Html.EditorFor(model => model.EmployeeSalary,
new { htmlAttributes = new { @class = "form-control" } })
42. @Html.ValidationMessageFor(model => model.Empl
oyeeSalary, "", new { @class = "text-danger" })
43. </div>
44. </div>
45.
46. <div class="form-group">
47. @Html.LabelFor(model => model.EmployeeCity, htmlAt
tributes: new { @class = "control-label col-md-2" })
48. <div class="col-md-10">
49. @Html.EditorFor(model => model.EmployeeCity, n
ew { htmlAttributes = new { @class = "form-control" } })
50. @Html.ValidationMessageFor(model => model.Empl
oyeeCity, "", new { @class = "text-danger" })
51. </div>
52. </div>
53.
54. <div class="form-group">
55. <div class="col-md-offset-2 col-md-10">
56. <input type="submit" value="Save" class="btn b
tn-default" />
57. </div>
58. </div>
59. </div>
60. }
61.
62. <div>
63. @Html.ActionLink("Back to List", "Index")
64. </div>
65.
66. @section Scripts {
67. @Scripts.Render("~/bundles/jqueryval")
68. }

Output

Step 19

Now we create view for viewing employee data. So create Action method detail with
parameter id . Using this we get data from database and pass it in view. Add view by
right clicking in method and selecting template Details.

1. public ActionResult Detail(int id)


2. {
3. var data = _context.Employees.Where(x => x.EmployeeId == id)
.FirstOrDefault();
4. return View(data);
5. }

1. @model CrudOperationInMVC.Controllers.Employee
2.
3. @{
4. ViewBag.Title = "Detail";
5. }
6.
7. <div>Detail</div>
8.
9. <div>
10. <div>Employee</div>
11. <hr />
12. <dl class="dl-horizontal">
13. <dt>
14. @Html.DisplayNameFor(model => model.EmployeeName)

15. </dt>
16.
17. <dd>
18. @Html.DisplayFor(model => model.EmployeeName)
19. </dd>
20.
21. <dt>
22. @Html.DisplayNameFor(model => model.EmployeeSalary
)
23. </dt>
24.
25. <dd>
26. @Html.DisplayFor(model => model.EmployeeSalary)

27. </dd>
28.
29. <dt>
30. @Html.DisplayNameFor(model => model.EmployeeCity)

31. </dt>
32.
33. <dd>
34. @Html.DisplayFor(model => model.EmployeeCity)
35. </dd>
36.
37. </dl>
38. </div>
39. <p>
40. @Html.ActionLink("Edit", "Edit", new { id = Model.Employee
Id }) |
41. @Html.ActionLink("Back to List", "Index")
42. </p>

Output

Step 20

Now we create Action Method for delete which takes id as n parameter.

1. public ActionResult Delete(int id)


2. {
3. var data = _context.Employees.Where(x => x.EmployeeId == id)
.FirstOrDefault();
4. _context.Employees.Remove(data);
5. _context.SaveChanges();
6. ViewBag.Messsage = "Record Delete Successfully";
7. return RedirectToAction("index");
8. }

Code Explanation
 Here first we get data by id from database.
 Remove that entity which we get from database.
 Save changes using SaveChanges() method.
 And redirect to Index method.
Output

Here are the whole controller codes.

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.Mvc;
6.
7. namespace CrudOperationInMVC.Controllers
8. {
9.
10.
11.
12. public class HomeController : Controller
13. {
14. TutorialsCS _context = new TutorialsCS();
15.
16. public ActionResult Index()
17. {
18. var listofData = _context.Employees.ToList();
19. return View(listofData);
20. }
21.
22. [HttpGet]
23. public ActionResult Create()
24. {
25. return View();
26. }
27.
28. [HttpPost]
29. public ActionResult Create(Employee model)
30. {
31. _context.Employees.Add(model);
32. _context.SaveChanges();
33. ViewBag.Message = "Data Insert Successfully";
34. return View();
35. }
36. [HttpGet]
37. public ActionResult Edit(int id)
38. {
39. var data = _context.Employees.Where(x => x.Employe
eId == id).FirstOrDefault();
40. return View(data);
41. }
42. [HttpPost]
43. public ActionResult Edit(Employee Model)
44. {
45. var data = _context.Employees.Where(x => x.Employe
eId == Model.EmployeeId).FirstOrDefault();
46. if (data != null)
47. {
48. data.EmployeeCity = Model.EmployeeCity;
49. data.EmployeeName = Model.EmployeeName;
50. data.EmployeeSalary = Model.EmployeeSalary;
51. _context.SaveChanges();
52. }
53.
54. return RedirectToAction("index");
55. }
56. public ActionResult Delete(int id)
57. {
58. var data = _context.Employees.Where(x => x.Employe
eId == id).FirstOrDefault();
59. _context.Employees.Remove(data);
60. _context.SaveChanges();
61. ViewBag.Messsage = "Record Delete Successfully";
62. return RedirectToAction("index");
63. }
64. public ActionResult Detail(int id)
65. {
66. var data = _context.Employees.Where(x => x.Employe
eId == id).FirstOrDefault();
67. return View(data);
68. }
69.
70. }
71. }

You might also like