Razor Pages CRUD operations in Asp.net Core

Let's learn how to work with database, CRUD Operation in Asp.Net Core Razor Pages

In this tutorial we will learn how to create, read, update, and delete (CRUD) in asp.net core razor page application, so we learn how work with database.

While working with database from razor pages you can use any data access mechanism like Ado.Net, Entity Framework etc.

Here in example we will be using Entity Framework.

Create a Asp.net Razor Page Project, then add a new page, here in example we have created a page for student, we learn how to add new student then read, edit and delete on the same page.

CRUD in Razor Page Application

Step 1: Create a page and design a form
Notice, in form, there is hidden field called StudentId, this will help to differentiate new and existing student

<form method="post">
@Html.HiddenFor(m => m.StudentId)
<div asp-validation-summary="ModelOnly" class="text-danger"> </div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"> </label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger"></span>
	</div>
	<div class="form-group">
		<label asp-for="Email" class="control-label"> </label>
		<input asp-for="Email" class="form-control" />
		<span asp-validation-for="Email" class="text-danger"> </span>
	</div>
	<div class="form-group">
		<label asp-for="Mobile" class="control-label"> </label>
		<input asp-for="Mobile" class="form-control" />
		<span asp-validation-for="Mobile" class="text-danger"> </span>
	</div>                
	<div class="form-group">
		<input type="submit" value="Save Student" class="btn btn-default" />
	</div>
</form>
    

Read Existing Students

@if (Model.Students != null)
{
foreach (Student s in Model.Students)
{
<div style="padding:5px;">
    @s.Firstname  @s.Lastname <a href="@Url.Action("index","student",new { sid=s.StuId})">Edit</a> | <a href="@Url.Action("delete","student",new { sid=s.StuId})">Delete</a>
</div>
}
}

Step 2:
Create database connection details in appsettings.json and Entity Framework class DbContext

"DbConnectionConfig": {
"DatabaseName": "MarketingDB",
"UserName": "masa",
"Password": "mapass",
"ServerName": "USER-PC"
}

Step 3:
Create a DTO class to interact with database using Entity Framework, in this class we have written four methods AddStudent, UpdateStudent, GetAllStudents, DeleteStudents, Learn IDisposable Implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AspNetCoreWebApplication.DTO
{
public class StudentDTO : IDisposable
{
public Student AddStudent(Student s)
{
using (EFContext context = new EFContext())
{
context.tbStudent.Add(s);
context.SaveChanges();
}
return s;
}
public Student UpdateStudent(Student student)
{
Student _s = null;
using (EFContext context = new EFContext())
{
_s = context.tbStudent
.Where(s => s.StuId == student.StuId)
.FirstOrDefault<Student>();
if (_s != null)
{
_s.Firstname = student.Firstname;
_s.Lastname = student.Lastname;
_s.Email = student.Email;
_s.ContactNumber = student.ContactNumber;
context.SaveChanges();
}
}
return _s;
}
public List<Student> GetAllStudents()
{
List<Student> list = new List<Student>();
var context = new EFContext();
list = context.tbStudent
.ToList<Student>();
return list;
}
public bool DeleteStudent(int stuid)
{
bool _isDeleted = false;
Student _s = null;
var context = new EFContext();
_s = context.tbStudent
.Where(s => s.StuId == stuid)
.FirstOrDefault<Student>();
if (_s != null)
{
context.tbStudent.Remove(_s);
context.SaveChanges();
_isDeleted = true;
}
return _isDeleted;
}
public Student GetStudent(int sid)
{
Student _s = null;
using (EFContext context = new EFContext())
{
_s = context.tbStudent
.Where(s => s.StuId == sid)
                     .FirstOrDefault<Student>();
            }
            return _s;
        }       
    }
}

Step 4:
In PageModel public class studentModel:PageModel {}

First we create model properties
[BindProperty]
public int StudentId { get; set; }
[BindProperty]
[Required(ErrorMessage = "Firstname Required")]
[StringLength(50, ErrorMessage = "5 to 50 characters.", MinimumLength = 3)]
public string FirstName { get; set; }
[BindProperty]
[Required(ErrorMessage = "Lastname Required")]
[StringLength(50, ErrorMessage = "5 to 50 characters.", MinimumLength = 3)]
        public string LastName { get; set; }
        [BindProperty]
        [Required(ErrorMessage = "Email Required")]
        [EmailAddress(ErrorMessage = "Invalid email")]
        public string Email { get; set; }
        [BindProperty]
        public string Mobile { get; set; }
        [BindProperty]
        public List<Student> Students { get; set; }

Setup property values in OnGet() method

public void OnGet()
{
    int _id = Convert.ToInt32(Request.Query["sid"]);
    Student _s = null;
    using (StudentDTO dto = new StudentDTO())
    {
        this.Students = dto.GetAllStudents();
        _s = dto.GetStudent(_id);
        if (_s != null)
        {
            this.StudentId = _s.StuId;
            this.Email = _s.Email;
            this.FirstName = _s.Firstname;
            this.LastName = _s.Lastname;
            this.Mobile = _s.ContactNumber;
        }
    }
}

Finally When form submitted, we capture the value and update database in OnPost() method

public IActionResult OnPost()
{
    Student _student = new Student();
    _student.Firstname = FirstName;
    _student.Lastname = LastName;
    _student.ContactNumber = Mobile;
    _student.Email = Email;
    _student.StuId = StudentId;
    using (StudentDTO dto = new StudentDTO())
    {
        if (_student.StuId == 0)
        {
            dto.AddStudent(_student);
        }
        else
        {
            dto.UpdateStudent(_student);
        }
    }
    return RedirectToPage("student", new{msg="updated"});
}
    

I hope you understood how to add, select, edit, delete data in asp.net razor page application



Asp.Net Core C# Examples | Join Asp.Net MVC Course