Introduction:

In this article we will learn how to complete CURD operation in asp.net core MVC razor page with Entity framework.Before getting started let’s know some basics about Razor pages.

Description:

This article we explain how to perform the Create, Read, Update, and Delete (CRUD) operations in ASP.NET Core MVC, using Entity Framework Core. We will use the "Database First" development approach generate model from database.  

What are Razor pages?

Razor Pages is a new feature of ASP.NET Core MVC that makes coding page-focused scenarios easier and more productive.

For more definition to go- https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-pages/?tabs=visual-studio.

Now let’s create a demo to achieve CURD operation using asp.net core MVC.

Create database following below script:

CREATE DATABASE collage 
GO
USE collage
GO
CREATE TABLE [dbo].[Student](
 [Id] [bigint] IDENTITY(1,1) primary key,
 [Name] [varchar](30) NULL, 
 [Phone] [varchar](20) NULL,
 [Address] [varchar](50) NULL,
 [City] [varchar](30) NULL,
 [Country] [varchar](30) NULL
 )

 Creating an ASP.NET Core Mvc Project

Open Visual Studio 2017 and let’s create a new ASP.NET Core Web Application project. To do this, select File > New > Project. In the New Project dialog select Visual C# > Web > ASP.NET Core Web Application just like in the figure below:


Figure 1: ASP.NET Core Web Application Project Template

Name your project to whatever you like, but for this exercise, we will name it as “AspDotNetCoreMvc” to confirm with the topic. Click OK and then select “Web Application (Model-View-Controller)” within ASP.NET Core templates as shown in the following figure below:


Figure 2: ASP.NET Core Web Application Template

Now click OK to let Visual Studio generate the required files needed for us to run the application. The figure below shows the default generated files:


Figure 3: The Models ,Views and Controller

Integrating Entity Framework Core

Now, right-click on the root of your application and then select Manage NuGet Packages. Select the Browse tab and in the search bar, type in “Microsoft.EntityFrameworkCore.SqlServer”. It should result to something like this:


Figure 4: Manage NuGet Package

 we are going to use Database-First development approach to work with existing database, we need to   install the additional packages below as well:

        ·         Microsoft.EntityFrameworkCore.Tools (v2.0.1)

        ·         Microsoft.EntityFrameworkCore.SqlServer.Design (v1.1.4)

 

Using Nuget Package Manager GUI

 Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution, then type in "Microsoft.EntityFrameworkCore.Tools”. Click install just like in the figure below:


Figure 5: Adding Microsoft.EntityFrameworkCore.Tools package

When it’s done installing all the required packages, you should be able to see them added to your project dependencies as shown in the figure below:


Figure 6: Entity Framework Core Packages installed

 

Creating Entity Models from Existing Database

 Using Package Manager Console

        Go to Tools –> NuGet Package Manager –> Package Manager Console

        And then run the following command below to create a model from the existing database:

 

Scaffold-DbContext "Integrated Security=SSPI;Persist Security
Info=False;Initial Catalog=collage;Data Source=(local)"Microsoft.EntityFrameworkCore.SqlServer
-OutputDir Models/DataBase

The Server attribute above is the SQL server instance name. You can find it in SQL Management Studio by right clicking on your database. For this example, the server name is “SSAI-L0028-HP\SQLEXPRESS”.

The Database attribute is your database name. In this case, the database name is “EFCoreDBFirstDemo”.

The –OutputDir attribute allows you to specify the location of the files generated. In this case, we’ve set it to Models/DataBase.

The command above will generate models from existing database within Models/DB folder. Here’s the screenshot below:


Figure 7: Entity Framework Generated Model

Now create Student Controller as shown in the figure below:



Figure 8: Controller Created

Now Go to Student Controller and right click on index action method and then Click Add view , after addning index view create two partial view _DeleteStudent.cshtml and _Student.cshtml as shown in the figure below:

 

Figure 9 Controller Created      

Now write code in index.cshtml.

index.cshtml

@model List<AspdotNetCoreMvc.Models.Student>
@using AspdotNetCoreMvc.Models
 
@{
    ViewData["Title"] = "Index";
}
 
<div class="top-buffer"></div>
<div class="panel panel-primary">
    <div class="panel-heading panel-head">Students</div>
    <div class="panel-body">
        <div class="btn-group">
            <a id="createEditStudentModal" data-toggle="modal" asp-action="AddEditStudent" data-
                   target="#modal-action-student"  class="btn btn-primary">
                <i class="glyphicon glyphicon-plus"></i>  Add Student
            </a>
        </div>
        <div class="top-buffer"></div>
       <table class="table table-bordered table-striped table-condensed">
           <thead>
                <tr>
                    <th>Name</th>
                    <th>Phone</th>
                    <th>Country</th>
                    <th>City</th>
                    <th>Address</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>@Html.DisplayFor(modelItem => item.Name)</td>
                        <td>@Html.DisplayFor(modelItem => item.Phone)</td>
                        <td>@Html.DisplayFor(modelItem => item.Country)</td>
                        <td>@Html.DisplayFor(modelItem => item.City)</td>
                        <td>@Html.DisplayFor(modelItem => item.Address)</td>
                        <td>
                  <a id="editstudentModal" data-toggle="modal" asp-action="AddEditstudent"
                asp-route-id="@item.Id" data-target="#modal-action-student" class="btn btn-info">
                                <i class="glyphicon glyphicon-pencil"></i>  Edit
                   </a>
                <a id="deletestudentModal" data-toggle="modal" asp-action="Deletestudent"
                asp-route-id="@item.Id" data-target="#modal-action-student" class="btn btn-danger">
                                <i class="glyphicon glyphicon-trash"></i>  Delete
                   </a>
                        </td>
                    </tr>
                }
            </tbody>
       </table>
    </div>
</div>
 <div id="modal-action-student" class="modal fade hidden-print" tabindex="-1" role="dialog">
   <div class="modal-dialog">
       <div class="modal-content">
 
       </div>
   </div>
</div>
@section scripts
    {
    <script src="~/js/index.js" asp-append-version="true"></script>
} 


Now Create index.js file as shown in the figure below:



Figure 10: index.js Created 

Now write Code in index.js

    (function ($) {
    function Student() {
        var $this = this;
 
        function initilizeModel() {
            $("#modal-action-student").on('loaded.bs.modal', function (e) {
                }).on('hidden.bs.modal', function (e) {
                    $(this).removeData('bs.modal');
                });
        }
        $this.init = function () {
            initilizeModel();
        }
    }
    $(function () {
        var self = new Student();
        self.init();
    })
}(jQuery))

Now write code in _Student.cshtml.

_Student.cshtml

@model AspdotNetCoreMvc.Models.Student  
   
<div class="modal-body">
        <h3>Add Student</h3>
        <hr />
        <form asp-action="AddEditstudent" role="form">
            <div class="row">
                <div class="col-md-12">
                    <label asp-for="Name"></label>
                    <input asp-for="Name" class="form-control" />
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <label asp-for="Address"></label>
                    <input asp-for="Address" class="form-control" />
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <label asp-for="Country"></label>
                    <input asp-for="Country" class="form-control" />
                </div>
            </div>
 
            <div class="row">
                <div class="col-md-12">
                    <label asp-for="City"></label>
                    <input asp-for="City" cl class="form-control" />
                </div>
            </div>
 
            <div class="row">
                <div class="col-md-12">
                    <label asp-for="Phone"></label>
                    <input asp-for="Phone" class="form-control" />
                </div>
            </div>
            <hr />
            <div class="row">
                <div class="col-md-12" style="text-align:right;">
                    <input type="submit" value="Save" class="btn btn-primary" />
                    <a class="btnbtn-default" href="#" data-dismiss="modal">Cancel</a>
                </div>
            </div>
 
 
        </form>
    </div>

 

Now write code in _DeleteStudent.cshtml.

_DeleteStudent.cshtml

@model AspdotNetCoreMvc.Models.Student
@using AspdotNetCoreMvc.Models
 
@using (Html.BeginForm())
{        <div class="modal-body form-horizontal">
        <h3>Delete Student</h3>
        <hr />
        Are you want to delete @Model.Name?
        <hr />
        <div class="row">
     <div class="col-md-12" style="text-align:right;">
        <input type="submit" value="Yes" class="btn btn-primary" />
         <a class="btn btn-default" href="#" data-dismiss="modal">No</a>
     </div>        </div>           </div>     }


Now write code in StudentController.

StudentController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspdotNetCoreMvc.Models;
namespace AspdotNetCoreMvc.Controllers
{
    public class StudentController : Controller
   {
 
       collageContext context = new collageContext();
       public IActionResult Index()
       {
          
            return View(context.Student.ToList());
       }
       [HttpGet]
       public IActionResult AddEditStudent(long? id)
       {
            Student model = new Student();
            if (id.HasValue)
            {
                Student student =context.Set<Student>().SingleOrDefault(c => c.Id == id.Value);
                if (student != null)
                {
                    model.Id = student.Id;
                    model.Name = student.Name;
                    model.Address =student.Address;
                    model.City = student.City;
                    model.Country =student.Country;
                    model.Phone =student.Phone;
                }
            }
            return PartialView("~/Views/Student/_Student.cshtml", model);
       }
 
       [HttpPost]
       public ActionResult AddEditStudent(long? id, Student model)
       {
            try
            {
                if (ModelState.IsValid)
                {
                    bool isNew = !id.HasValue;
                    Student student = isNew ? new Student()
                    :context.Set<Student>().SingleOrDefault(s => s.Id == id.Value);
                    student.Name = model.Name;
                    student.Phone =model.Phone;
                    student.Country =model.Country;
                    student.City = model.City;
                    student.Address =model.Address;
                    if (isNew)
                    {
                        context.Add(student);
                    }
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return RedirectToAction("Index");
       }
 
        [HttpGet]
       public IActionResultDeleteStudent(long id)
       {
            Student model =context.Set<Student>().SingleOrDefault(c => c.Id == id);            
            return PartialView("~/Views/student/_DeleteStudent.cshtml", model);
       }
       [HttpPost]
       public IActionResult DeleteStudent(long id,Student model)
       {
            Student student =context.Set<Student>().SingleOrDefault(c => c.Id == id);
            context.Entry(student).State =Microsoft.EntityFrameworkCore.EntityState.Deleted;
            context.SaveChanges();
            return RedirectToAction("Index");
       }
   }
}

 

Now build and run the application using CTRL + 5. In the browser, navigate to /student. It should bring up the following page.



Figure 11: Student List

 

If you want to create new student click on Add Student button then open popup as shown in the figure below:


.Figure 12: New Student

 

If you want to Edit Student Record click on Edit button then open popup as shown in the figure below:


Figure 13: Edit Student

 

If you want to Delete Student Record click on Delete button then open popup as shown in the figure below:


Figure 14: Delete Student 

After clicking “Yes” button student record will be deleted from database.


I hope it will help to you.

 

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.