Introduction

In my previous article I discussed how we can select and insert data using EF by using LIST and Create option.

In following image we can see that there is Edit link

		
		MVC Scaffolding using EF
		
Figure 1

If we click on Edit link we will get error as we didn’t added Edit action in my controller.

		
		MVC Scaffolding Edit using EF part 1
		
		Figure 2
		
		

When I clicked the Edit button of 2nd row its showing me the error. In image you can see that it’s also taking the stu_id which I bound with actionlink at the time of Scaffolding List option.

Note: - if you are new to actionlink then click here.

Now add action for Edit which is taking the id as parameter which is passed by actionlink.

		
		public ActionResult Edit(int id)
        {

            return View();
        
        }

		
		

Now right click on Edit action and add View and you will get following window:-

		
		Scaffolding Edit option using EF
		
		Figure 3
		
		

Select the model class and select scaffold template Edit and click on Add button.

After clicking on Add button you will get the Edit.cshtml. In this file on top you will see the object of model.

		
		Create Edit of Scaffolding in MVC
		
		Figure 4
		
		

So we need to pass the object of model so that Edit.cshtml form will be filled.

Following code will be added to perform the Edit Action

Controller Code

		
		[HttpGet]
        [ActionName("Edit")]
        public ActionResult Edit_Get(int id)
        {

            scaff_efEntities scaff = new scaff_efEntities();
            student stu = scaff.students.Find(id);
            return View(stu);
        }

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int id)
        {

            scaff_efEntities scaff = new scaff_efEntities();
            student stu = scaff.students.Find(id);
            UpdateModel(stu);
            scaff.SaveChanges();
            return View();
        }

		
		

Note:-please click here for the explanation of this code

Now execute this code and you will get following output:-

		
		MVC Scaffolding Edit option 
		
		Figure 5
		
		

Now change the data accordingly:-

Note: - you can remove column from Edit.cshtml which you don’t want to update like stu_id, name etc.

		
		Scaffolding Edit output
		
		Figure 6
		
		

Now click on save button and click on Back to List

		
		Scaffolding Edit output with Ef
		
		Figure 7
		
		

Email Address

For any query you can mail me at Malhotra.isha3388@gmail.com.