Introduction

In my last article I have explained how to use LIST option of scaffolding using Entity Framework. After completing the LIST option we got following output:-

		
		MVC Scaffolding using EF
		
Figure 1

In this article I will explain how to use Scaffolding Create option using Entity Framework. in my previous article series I explained how to use this option using LINQ.

Using Create option we insert data in table. As we know that we have only Index action in our Home Controller so if we click on Create New link which is showing in the figure I will get an error as this action is not found and we will get following error:-

		
		MVC Scaffolding Create using EF part 1
		
		Figure 2
		
		

So first of all add Create action in home controller

		
		public ActionResult Create()
        {

            return View();
        
        }

		
		

Now add view for Create action. So right click on Create() and select Add View and you will get following window:-

		
		Scaffolding Create option using EF
		
		Figure 3
		
		

In this window select Model class which is student and select Create option from Scaffold Template and click on Add button.

As you clicked on add button Create view will be created.

Now again execute the code and click on Create New link and you will find the following window:-

		
		Create option of Scaffoding in MVC
		
		Figure 4
		
		

As we know that stu_id is an Identity so we need not to add this column. So we can remove this column from our page. Similarly we can customize our form using others controls according to need. So delete this code from your view and again execute this form.

		
		MVC Scaffolding create 
		
		Figure 5
		
		

Now when we click on Create button we need to get the data of controls so we need to overload the Create action and set the get and post tag accordingly. Then we will add code for insertion using EF.

Controller Code

		
		[HttpGet]
        public ActionResult Create()
        {

            return View();
        
        }

        [HttpPost]
        public ActionResult Create(student stu)
        {
            scaff_efEntities scaff = new scaff_efEntities();
            scaff.students.Add(stu);
            scaff.SaveChanges();

            return View();

        }

		
		

Note:- if you are new to Entity Framework then Click here to understand the insert option in EF.

Now execute the code and fill the data and then click on Create button

		
		MVC Scaffolding create option 
		
		Figure 6
		
		

Now click on Back to List and you will find your data

		
		Scaffolding create output
		
		Figure 7
		
		

Email Address

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