Thursday, 24 December 2020

CRUD Operation in MVC Using Entity Framework 6.0 - Part 3

It is 3rd Part of the Entity framework 6.0 code first using MVC. Please visit previous articles from below link before reading this. 

Part1 

Part2

Here, I will show you how to Edit and Delete resource using EF6.0 code first in MVC. As we discussed for modifying resource/data in database it is recommend using [HttpPost] attribute.

Let’s open EmployeeController.cs file and add Edit action method.


As we disused in previous article for showing/reading data recommend to use [HttpGet] attribute and we also discussed in previous article by default all action method is Get method. You can remove [HttpGet] attribute from above screen and check it will work and go to developer console and Check Http method type.

Now right click on Edit action method and select Add View.


It will create Edit.cshtml file in Employee folder under Views. If we run application and navigate to Edit view it show UI but cannot save the changes to database.  Let’s run application and check this.


Click on Edit action link and it navigate to Edit action View. It means we are passing employee Id and in Get method of Edit it searches employee with that ID and load below View. Modify City from Nagpur to Amravati and Click on Save button, you will get resource not found error on browser because we didn’t write any code for storing data on click of save button for that need to create Post action method of Edit to store data into database.


One more thing, Edit action link on Index view contains employee Id and it pass as parameter to Get action method of Edit. Save for Details and Delete action method.

 

Now create Post action method for Edit

 


If you noticed I used Employee model as parameter highlighted above and for Create, I used FormCollection. You can use anything both work file even you can pass parameter also (FirstName, LastName, City). But make name attribute of textbox matches with parameter name.

Now run application and check it. I navigate to Edit view and change City from Nasik to Bhandara.

 

You can observe updated data gets loaded in Index view of Employee controller.

 

We almost cover all scenario, now try to implement Delete action method for Get and Post from your side. Let me know for any issue in comments will help you.

 

 

 

 

 

 

 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home