Implementing CRUD Operation With Entity Framework in Asp.net MVC: Part II


In the previous article, we were able to add a data layer to our demo application using the Database first approach with Ado.Net. In this article, we are going to create MVC pages to interact with the database.

Let us start by adding Student Controller. To achieve this, right click on the controller folder > Add > Controller. Select MVC 5 Controller- Empty then Click Add.

Let us name the controller ‘Student’.



Click on Add and wait for the visual studio to complete the process.

Right click on the index method generated by VS to add Index view



Click on add and wait for the visual studio to complete the process.

Visual studio generated an empty index view.

Before we build and launch the solution, let us set the Student index page as the landing page for this demo application. In the solution explorer, navigate to App_Start > RouteConfig.

Edit the RouteConfig and change the controller to ‘Student’ as shown



Also, modify the Layout as shown


    
    
    
    

    

    @ViewBag.Title - CRUD Demo
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    
    
    
@RenderBody()
© @DateTime.Now.Year - CRUD Demo
@Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)

Save all the changes, build and run the solution, you should have an index page similar to :




Modify the index page, add a button to create new student and table to display students.



   
 @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    

Students

S/N Name Email Phone Number Date of Birth Address Actions
||

Let us add student collection to be displayed on the index page. We start by creating a view model for the Student class generated by the Entity framework. By this approach, we are creating a layer on top of our database object and we are sure that we are not exposing directly the table structure.

Add a new class called StudentViewModel to the model's folder.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCSampleCRUDOperation.Models
{
    public class StudentViewModel
    {
        public int Student_Id { get; set; }
        public string Student_Name { get; set; }
        public Nullable Student_Age { get; set; }
        public string Student_Email { get; set; }
        public string Phone_Number { get; set; }
        public Datetime? Student_DOB { get; set; }
        public string Address_Line1 { get; set; }
        public string Address_Line2 { get; set; }
    }
}
This view model (StudentViewModel) will be used as a data transfer object between the view pages, controllers and the database object.

Modify the Student controller as follows


using MVCSampleCRUDOperation.Models;
using MVCSampleCRUDOperation.Models.DataAccessLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCSampleCRUDOperation.Controllers
{
    public class StudentController : Controller
    {
        MVCSampleCRUD_DBEntities dbContext = new MVCSampleCRUD_DBEntities(); 
        public ActionResult Index()
        {
            var model = dbContext.Students.Select(m=>new StudentViewModel()
            {
                Student_Id=m.Id,
                Student_Age=m.Age,
                Student_DOB=m.DOB,
                Student_Email=m.Email,
                Student_Name=m.Name,
                Address_Line1=m.AddressLine1,
                Address_Line2=m.AddressLine2,
                Phone_Number=m.PhoneNumber

            }).ToList();

            return View(model);
        }
        protected override void Dispose(bool disposing)
        {
            dbContext.Dispose();
            base.Dispose(disposing);
        }
    }
}



On the controller, we created an instance of the context class, we also added a Dispose method to properly dispose our database context. List of the student was also spooled and sent to the index page as a model.

Let us now modify the index page to use the model.

   
 @model IEnumerable < mvcsamplecrudoperation.models.studentviewmodel = "" >
    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    

Students

@{ int i = 1; } @foreach (var item in Model) { i++; }
S/N Name Email Phone Number Date of Birth Address Actions
@i @item.Student_Name @item.Student_Email @item.Phone_Number @item.Student_DOB.Value.ToString("dd-MM-yyyy") @{$"{item.Address_Line1} {item.Address_Line2}"} ||

First, we added a collection of students as a model, we now modify the table body to loop through the model taking advantage of the Razor view engine which enables us to combine C# codes with HTML. You can learn more on Razor codes in MVC.

Save all the changes, build and run the solution, you should have the following




Since there is no record yet in the student table, the table is empty.

Now, let us add a "create page" to the solution so as to bring in new students to our collection.

Add the following method to Student controller



 public ActionResult CreateStudent()
  {
         
      return View();
  }


Right-click on the method name and select add view, wait for the visual studio to complete the process. Modify the generated view as follow:

    @model MVCSampleCRUDOperation.Models.StudentViewModel
    @{
        ViewBag.Title = "CreateStudent";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    

Create Student

@using (Html.BeginForm("CreateStudent", "student", FormMethod.Post, new { @class = "form-horizontal", id = "newStudentForm" })) {
@Html.ValidationSummary()

@Html.TextBoxFor(model => model.Student_Name, new { placeholder = "Full Name", @class = "form-control" })

@Html.TextBoxFor(model => model.Student_Email, new { placeholder = "Email", @class = "form-control" })

@Html.TextBoxFor(model => model.Phone_Number, new { placeholder = "Phone Number", @class = "form-control" })

@Html.TextBoxFor(model => model.Student_DOB, new { placeholder = "Date of Birth [mm/dd/yyyy]", @class = "form-control" })

@Html.TextBoxFor(model => model.Address_Line1, new { placeholder = "Line 1", @class = "form-control" })
@Html.TextBoxFor(model => model.Address_Line2, new { placeholder = "Line 2", @class = "form-control" })
Close
}

In the above code, we added the student model and we created a strongly typed form. Three buttons were added to submit the form, reset and go back to the student index page.

Replace the create button on the index page with the following


Save all changes, build and run the project. Click on create new student button you should have the following




Let us add post action method to the student controller

On the student controller, add the following method


 [HttpPost]
        public ActionResult CreateStudent(StudentViewModel model)
        {

            try
            {
                var student = new Student()
                {
                    Name = model.Student_Name,
                    PhoneNumber = model.Phone_Number,
                    DOB = model.Student_DOB,
                    Email = model.Student_Email,
                    AddressLine1 = model.Address_Line1,
                    AddressLine2 = model.Address_Line2,
                    Age = DateTime.Now.Subtract(model.Student_DOB.Value).Days
                };
                dbContext.Students.Add(student);
                if (dbContext.SaveChanges() > 0)
                {
                    return RedirectToAction("Index");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("",$"Error {ex?.Message}");
                return View(model);
            }
   ModelState.AddModelError("", "Error occurred while saving record, please try again");
            return View(model);
        }


Note that the post method ‘CreateStudent’ have the same name as the previous method but it is decorated with ‘HttpPost’ attribute. This allows the compiler to know which method to call for post action and get action.

The method takes a parameter of type ‘StudentViewModel ‘. On submitting a new student, the compiler will automatically bind the submit data to ‘StudentViewModel ‘ because the student form is strongly typed of ‘StudentViewModel’. New Student object is now created and added to the student context. SaveChanges method of dbcontext is called to persist the data into the database, if this process is successful, the page will be redirected to the index page but if it fails, the Create page is returned with the model, and an error message added to ModelState.

Save all changes, build and run the project.
Navigate to the student creation page and add a new student.

Note that no validation was added, but we have tried to catch any exception that may occur when posting new student using try catch.
This project was also intended to be kept as simple as much as possible.

In this article, we demonstrated how to persist data into the database using Entity framework and MVC. In the next article, we will focus on previewing, editing and deleting a student from the database.


Previous Article                                                                                                                   Next Article


Implementing CRUD Operation With Entity Framework in Asp.net MVC: Part II Implementing CRUD Operation With Entity Framework in Asp.net MVC: Part II Reviewed by Akintunde Toba on March 06, 2019 Rating: 5

No comments:

Home Ads

Powered by Blogger.