Bind Add Update Delete Data Using MVC Entity Framework And LINQ

Introduction

In this article, we will learn to bind, insert, update and delete the data, using MVC and Entity Framework. I am new in MVC, I've worked enough in Web forms but now, I just switched to MVC. Thus, I'm trying to learn it step by step. I am taking my friend's help in this and after his help, I will try to create a simple add update Application in MVC, which I will share with you people, so that those who are new in MVC like me can help themselves out, if they are stuck somewhere. Thus, let's not waste time and start developing our Web Application.
 
Description

First, we will create a table, in which we want to insert our data from the Web Application. Before that, we will create a database first, write the query, given below to do this, using GUI.
  1. Create Databse

     

    Write the query, given above and execute the query. It will create our database now. We need to create a table, write the query, given below-

  2. Create Table


    Execute the query, given above and it will create the table in our database. Now, our table is ready. Thus, let's start with our code section. Now, follow the following steps in your Visual Studio to create a new MVC project.

  3. Create new project

Now, it will ask you, what kind of Application, you want to create, you have to choose MVC, as given below:

new
 
You can see in the image, shown above, that we give the name for this Application and the location, where we want to store this Application. Now, it will ask us about the template, we want to use, as given below-

template

We choose Internet template, because it will give us some default build in Home control and view like Home, AboutUs etc. and also some scripts, which we can use for the validation. You can use other templates also, but here we will do this with this template.
 
Now, we will create a new Class Library. Using Entity Framework, we can create this with the same project, we created. To make it clean, we will create this outside this template. Let's see how to add:

template

Right click on the solution, add new project, select Class Library, name it StudentDataEntity, add a folder within it and name that folder as StudentModel. Now, we will add Entity Framework within this folder, right click on the folder, add new item and select the data from left side and select Entity Model like image, given below-

Entity Model
 
Second Image is given below-

entity model
 
Now, select the object, you want to use through this Entity Framework.

table

Now, build this and after this, add this Library reference to our Application.

After adding the reference to your Application, you will see App.Config file in Entity Library. From the file, cut the connection string and add this into your Web.Config file. Now, we start coding. Go to your Home controller and open index from view folder, remove everything from index view page. We will add an anchor link out there to insert the data in the database.



Using HTML Helper class, we will create an anchor link here, and now, we will create InsertData action in Home Controller. Now, we will create an Action to insertData and we will create view for inserting Data.
  1. public ActionResult InsertData()  
  2. {  
  3.     return View();  

Now, we will create a view for this. We need form fields to insert the data into the table. Thus, we will use the model in the view and HTML helper class to create a form.
  1. @model StudentDataEntity.StudentModel.tbl_Students  
  2.   
  3. @{  
  4.     ViewBag.Title = "InsertData";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>InsertData</h2>  
  9. @ViewBag.Success  
  10. @using (Html.BeginForm("InsertData","Home",FormMethod.Post)) {  
  11.     @Html.AntiForgeryToken()  
  12.     @Html.ValidationSummary(true)  
  13.   
  14.     <fieldset>  
  15.         <legend>tbl_Students</legend>  
  16.   
  17.         <div class="editor-label">  
  18.             @Html.LabelFor(model => model.Firstname)  
  19.         </div>  
  20.         <div class="editor-field">  
  21.             @Html.EditorFor(model => model.Firstname)  
  22.             @Html.ValidationMessageFor(model => model.Firstname)  
  23.         </div>  
  24.   
  25.         <div class="editor-label">  
  26.             @Html.LabelFor(model => model.Lastname)  
  27.         </div>  
  28.         <div class="editor-field">  
  29.             @Html.EditorFor(model => model.Lastname)  
  30.             @Html.ValidationMessageFor(model => model.Lastname)  
  31.         </div>  
  32.   
  33.         <div class="editor-label">  
  34.             @Html.LabelFor(model => model.Class)  
  35.         </div>  
  36.         <div class="editor-field">  
  37.             @Html.EditorFor(model => model.Class)  
  38.             @Html.ValidationMessageFor(model => model.Class)  
  39.         </div>  
  40.   
  41.         <div class="editor-label">  
  42.             @Html.LabelFor(model => model.Section)  
  43.         </div>  
  44.         <div class="editor-field">  
  45.             @Html.EditorFor(model => model.Section)  
  46.             @Html.ValidationMessageFor(model => model.Section)  
  47.         </div>  
  48.   
  49.         <div class="editor-label">  
  50.             @Html.LabelFor(model => model.Rollnumber)  
  51.         </div>  
  52.         <div class="editor-field">  
  53.             @Html.EditorFor(model => model.Rollnumber)  
  54.             @Html.ValidationMessageFor(model => model.Rollnumber)  
  55.         </div>  
  56.   
  57.         <div class="editor-label">  
  58.             @Html.LabelFor(model => model.IsActive)  
  59.         </div>  
  60.         <div class="editor-field">  
  61.             @Html.EditorFor(model => model.IsActive)  
  62.             @Html.ValidationMessageFor(model => model.IsActive)  
  63.         </div>  
  64.   
  65.         <p>  
  66.             <input type="submit" value="Create" />  
  67.         </p>  
  68.     </fieldset>  
  69. }  
  70.   
  71. <div>  
  72.     @Html.ActionLink("Back to List", "Index")  
  73. </div>  
  74.   
  75. @section Scripts {  
  76.     @Scripts.Render("~/bundles/jqueryval")  

We used model class, given above and used its properties to create a form and in the form, we mentioned the Action Name and Controller Name and method to submit the form data. You can see that, we have mentioned the same Action Name in the form, but we can't have the same action name with the same parameter, but we can create POST or we can use Method Overloading concept in this. Here, we will create an Action with the POST type and will use Entity Framework and LINQ to insert the data.
  1. [HttpPost]  
  2. public ActionResult InsertData(tbl_Students objStudent) 
  3. {  
  4.      if(ModelState.IsValid)  
  5.        {  
  6.           objContext.tbl_Students.Add(objStudent);  
  7.           objContext.SaveChanges();  
  8.           if(objStudent.id>0)  
  9.             {  
  10.               ViewBag.Success = "Inserted";  
  11.   
  12.             }  
  13.             ModelState.Clear();  
  14.        }  
  15.       return View();  

That's it, we write the code to Insert Data into Table. Let's run the code and check if this work or not.

 
Our form is ready. If we fill the data and it will be all aved in database, you will get the message inserted the way, you can see, given in the form, above. Thus, our next step will be to insert the data. Now, we need to bind this data, so we will write the code in Index Action and in Index View. Let's do this, as follows-
  1. public ActionResult Index()  
  2. {  
  3.     var objStudentList = objContext.tbl_Students.ToList();  
  4.     return View(objStudentList);  

Here, we get the data from the model and pass it to the view. Now, let's write the code in Index View, as follows-
  1. @model IEnumerable<StudentDataEntity.StudentModel.tbl_Students>  
  2. @{  
  3.     ViewBag.Title = "Home Page";  
  4. }  
  5. @Html.ActionLink("Insert Record", "InsertData")  
  6. <table>  
  7.     <thead>  
  8.         <tr>  
  9.             <th>Firstname</th>  
  10.             <th>Lastname</th>  
  11.             <th>Class</th>  
  12.             <th>Section</th>  
  13.             <th>Rollnumber</th>  
  14.             <th>IsActive</th>  
  15.             <th>Action</th>  
  16.         </tr>  
  17.     </thead>  
  18.     <tbody>  
  19.         @foreach(var student in Model){  
  20.         <tr>  
  21.             <td>  
  22.                 @student.Firstname  
  23.             </td>  
  24.             <td>  
  25.                 @student.Lastname  
  26.             </td>  
  27.             <td>  
  28.                 @student.Class  
  29.             </td>  
  30.             <td>  
  31.                 @student.Section  
  32.             </td>  
  33.             <td>  
  34.                 @student.Rollnumber  
  35.             </td>  
  36.             <td>  
  37.                 @student.IsActive  
  38.             </td>  
  39.             <td>  
  40.                 @Html.ActionLink("Edit", "EditStudent", new {studentid=@student.id })|@Html.ActionLink("Delete", "DeleteStudent", new { studentid = @student.id })
  41.             </td>  
  42.         </tr>     
  43.         }  
  44.     </tbody>  
  45. </table> 
Now, the  time has come to check if it's working or not.
output

Thus, data is bound nicely. Hence, we already learned how we can insert and bind the data. Now, we just need to learn, how we can update and delete in MVC. Thus, on edit button, you can see that, we have given an Action Name (EditStudent), so we will create an Action Now Edit Student, as follows-
  1. public ActionResult EditStudent(Int32 studentid)  
  2. {  
  3.             var Studentdata = objContext.tbl_Students.Where(x => x.id == studentid).FirstOrDefault();  
  4.             if(Studentdata!=null)  
  5.             {  
  6.                 TempData["StudentID"] = studentid;  
  7.                 TempData.Keep();  
  8.                 return View(Studentdata);  
  9.             }  
  10.             return View();  

We created an Action with the name EditStudent and passed Id in it. Using LINQ query, we get the details of the student. Now, we will create the view, same as Insert view and we just have to change the action name in form. 
  1. @model StudentDataEntity.StudentModel.tbl_Students  
  2.   
  3. @{  
  4.     ViewBag.Title = "EditStudent";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>EditStudent</h2>  
  9.   
  10. @using (Html.BeginForm("EditStudent","Home",FormMethod.Post)) {  
  11.     @Html.AntiForgeryToken()  
  12.     @Html.ValidationSummary(true)  
  13.   
  14.     <fieldset>  
  15.         <legend>tbl_Students</legend>  
  16.   
  17.         @Html.HiddenFor(model => model.id)  
  18.   
  19.         <div class="editor-label">  
  20.             @Html.LabelFor(model => model.Firstname)  
  21.         </div>  
  22.         <div class="editor-field">  
  23.             @Html.EditorFor(model => model.Firstname)  
  24.             @Html.ValidationMessageFor(model => model.Firstname)  
  25.         </div>  
  26.   
  27.         <div class="editor-label">  
  28.             @Html.LabelFor(model => model.Lastname)  
  29.         </div>  
  30.         <div class="editor-field">  
  31.             @Html.EditorFor(model => model.Lastname)  
  32.             @Html.ValidationMessageFor(model => model.Lastname)  
  33.         </div>  
  34.   
  35.         <div class="editor-label">  
  36.             @Html.LabelFor(model => model.Class)  
  37.         </div>  
  38.         <div class="editor-field">  
  39.             @Html.EditorFor(model => model.Class)  
  40.             @Html.ValidationMessageFor(model => model.Class)  
  41.         </div>  
  42.   
  43.         <div class="editor-label">  
  44.             @Html.LabelFor(model => model.Section)  
  45.         </div>  
  46.         <div class="editor-field">  
  47.             @Html.EditorFor(model => model.Section)  
  48.             @Html.ValidationMessageFor(model => model.Section)  
  49.         </div>  
  50.   
  51.         <div class="editor-label">  
  52.             @Html.LabelFor(model => model.Rollnumber)  
  53.         </div>  
  54.         <div class="editor-field">  
  55.             @Html.EditorFor(model => model.Rollnumber)  
  56.             @Html.ValidationMessageFor(model => model.Rollnumber)  
  57.         </div>  
  58.   
  59.         <div class="editor-label">  
  60.             @Html.LabelFor(model => model.IsActive)  
  61.         </div>  
  62.         <div class="editor-field">  
  63.             @Html.EditorFor(model => model.IsActive)  
  64.             @Html.ValidationMessageFor(model => model.IsActive)  
  65.         </div>  
  66.   
  67.         <p>  
  68.             <input type="submit" value="Save" />  
  69.         </p>  
  70.     </fieldset>  
  71. }  
  72.   
  73. <div>  
  74.     @Html.ActionLink("Back to List", "Index")  
  75. </div>  
  76.   
  77. @section Scripts {  
  78.     @Scripts.Render("~/bundles/jqueryval")  

Now, we have to create an Action with HTTP Post EditStudent and will pass the model in it, as given below-
  1. [HttpPost]  
  2.         public ActionResult EditStudent(tbl_Students objStudnet)  
  3.         {  
  4.             Int32 StudentId = (int)TempData["StudentId"];  
  5.             var StudentData = objContext.tbl_Students.Where(x => x.id == StudentId).FirstOrDefault();  
  6.             if(StudentData!=null)  
  7.             {  
  8.                 StudentData.Firstname = objStudnet.Firstname;  
  9.                 StudentData.Lastname = objStudnet.Lastname;  
  10.                 StudentData.Rollnumber = objStudnet.Rollnumber;  
  11.                 StudentData.Class = objStudnet.Class;  
  12.                 StudentData.IsActive = objStudnet.IsActive;  
  13.                 objContext.Entry(StudentData).State = EntityState.Modified;  
  14.                 objContext.SaveChanges();  
  15.             }  
  16.             return RedirectToAction("Index");  
  17.         } 
Now, time to run the code for updating and we will see the result, as follows-



Now, we are left with Delete only. Thus, let's create an Action for Delete now.
  1. public ActionResult DeleteStudent(int studentid)  
  2.         {  
  3.             if (studentid > 0)  
  4.             {  
  5.                 var studentbyid = objContext.tbl_Students.Where(x => x.id == studentid).FirstOrDefault();  
  6.                 if (studentbyid != null)  
  7.                 {  
  8.                     objContext.Entry(studentbyid).State = EntityState.Deleted;  
  9.                     objContext.SaveChanges();  
  10.                 }  
  11.             }  
  12.             return RedirectToAction("Index");  
  13.         } 
We finish all the functionality for Delete too. Finally, we created a simple Add, Update, Delete in MVC, using Entity Framework.