Hi, Today I am going to perform crud operation with razor pages in asp.net core 3.1 and SQL Database.Here we will create a register user page, details user page and edit user page and also we will follow the code first approach with data migration.We will check validation of the fields. Now Let's see step by step.
Note: I hope you have installed 2019 visual studio.
Introduction
- Razor Page is a new feature of ASP.NET Core MVC that makes coding page-focused scenarios easier and more productive
- Razor pages is not just for simple scenarios, everything that you can do with MVC you can do by using Razor pages like Routing, Models, ActionResult, Tag Helpers and so on.
- Razor Page have two parts
- Razor Page(UI/View)
- Page Model(Contains Handlers)
Look our final output
Step 1: Create a project
Open visual studio and click on create a new project
Select ASP.NET Core Web Application and Click on next button
Now give the project name and click on create button
Select core 3.1 and select Web Application and click on create button
Step 2: Install necessary Package from NuGet Package manager
Right click on project and select NuGet Package Manager and install bellow library mentioned in below
Step 3: Adding Connection string
Open appsettings.json add SQL connection string
Step 4: Creating model class and DbContext class
Right click our root project folder and add a folder and give the folder and name Model.
In side the Model we will add two classes one is our model class and another is DbContext class. Right click on Model folder and a class.
User.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CRUDExamCor.Model
{
public class User
{
[Key]
public int UserId { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string EmailId { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string Mobile { get; set; }
[Required]
public string PinCode { get; set; }
}
}
Again Right click on Model folder and a class.
UserDBContext.cs
using Microsoft.EntityFrameworkCore;
namespace CRUDExamCor.Model
{
public class UserDBContext : DbContext
{
public UserDBContext(DbContextOptions<UserDBContext>
options) : base(options)
{
}
public DbSet<User>
users { get; set; }
}
}
Step 5: Generating database
Go to Tool option in visual studio -> Select NuGet Package Package Manager -> Package Manager Console
Now write below command in cmd
Add-Migration UserListDettails
after complete again run below command
update-database
Now open sql server and check newly created database and table
Step 6: Adding the functionality for user details
Go in Page folder and add a new folder UserList
Right click on UserList folder -> Select Add option -> Select Razor Page -> Again select Razor page on top and click Add button
Expand the Index.cshtml and open Index.cshtml.cs class and write below code for Bind the user details
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CRUDExamCor.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
namespace CRUDExamCor
{
public class IndexModel : PageModel
{
private readonly UserDBContext
_objEntity;
public IndexModel(UserDBContext
objEntity)
{
_objEntity = objEntity;
}
public
IEnumerable<User> users { get; set; }
public async Task OnGetAsync()
{
users = await
_objEntity.users.ToListAsync();
}
public async
Task<IActionResult> OnPostDelete(int id)
{
var book = await _objEntity.users.FindAsync(id);
if(book == null)
{
return NotFound();
}
_objEntity.users.Remove(book);
await _objEntity.SaveChangesAsync();
return RedirectToPage("Index");
}
}
}
Now open Index.cshtml and razor view code
@page
@model
CRUDExamCor.IndexModel
<br />
<div class="container row p-0 m-0">
<div class="col-9">
<h2 class="text-info"> User List </h2>
</div>
<div class="col-3">
<a asp-page="Create" class="btn btn-info
form-control text-white">Create New User</a>
</div>
<div class="col-12 border
p-3 mt-3">
<form method="post">
@if (Model.users.Count() > 0)
{
<table class="table table-striped border">
<tr class="table-secondary
text-info">
<th>
<label asp-for="users.FirstOrDefault().UserName"></label>
</th>
<th>
<label asp-for="users.FirstOrDefault().EmailId"></label>
</th>
<th>
<label asp-for="users.FirstOrDefault().Address"></label>
</th>
<th>
<label asp-for="users.FirstOrDefault().Mobile"></label>
</th>
<th>
<label asp-for="users.FirstOrDefault().PinCode"></label>
</th>
<th>
Action
</th>
</tr>
@foreach (var item in Model.users)
{
<tr>
<td>
@Html.DisplayFor(m => item.UserName)
</td>
<td>
@Html.DisplayFor(m => item.EmailId)
</td>
<td>
@Html.DisplayFor(m => item.Address)
</td>
<td>
@Html.DisplayFor(m => item.Mobile)
</td>
<td>
@Html.DisplayFor(m => item.PinCode)
<td>
<button asp-page-handler="Delete" asp-route-id="@item.UserId" onclick="return confirm('Are you sure do you want to delete?')" class="btn btn-danger
btn-sm">Delete</button>
<a asp-page="Edit" asp-route-id="@item.UserId" class="btn btn-success btn-sm text-white">
Edit
</a>
</td>
</tr>
}
</table>
}
else
{
<p>
No data available.
</p>
}
</form>
</div>
</div>
Now open the shared folder and open _Layout.cshtml page and add the code for navigation the page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,
initial-scale=1.0" />
<title>@ViewData["Title"]
- CRUDExamCor</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar
navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom
box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">CRUDExamCor</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle
navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse
d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav
flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link
text-dark" asp-area="" asp-page="/UserList/Index">User</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top
footer text-muted">
<div class="container">
© 2020 - CRUDExamCor - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts",
required: false)
</body>
</html>
We have completed the functionality for bind the user details
Now run the application and see the result
Step 7: Adding the functionality for Add User
Right click on UserList folder -> Select Add option -> Select Razor Page -> Again select Razor page on top and click Add button
Give the name as Create
Expand the Create.cshtml and open Create.cshtml.cs class and write below code for Add the user details
using System.Threading.Tasks;
using CRUDExamCor.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace CRUDExamCor
{
public class CreateModel : PageModel
{
private readonly UserDBContext
_objEntity;
public CreateModel(UserDBContext
objEntity)
{
_objEntity = objEntity;
}
[BindProperty]
public User user { get; set; }
public void OnGet()
{
}
public async
Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
await _objEntity.users.AddAsync(user);
await _objEntity.SaveChangesAsync();
return RedirectToPage("Index");
}
else
{
return Page();
}
}
}
}
Now open Create.cshtml and razor view code
@page
@model
CRUDExamCor.CreateModel
@{
ViewData["Title"] = "Create";
}
<br />
<h2 class="text-info">
Create New User
</h2>
<div class="border container" style="padding:30px">
<form method="post">
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.UserName"></label>
</div>
<div class="col-6">
<input asp-for="user.UserName" class="form-control" />
<span asp-validation-for="user.UserName" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.EmailId"></label>
</div>
<div class="col-6">
<input asp-for="user.EmailId" class="form-control" />
<span asp-validation-for="user.EmailId" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.Address"></label>
</div>
<div class="col-6">
<input asp-for="user.Address" class="form-control" />
<span asp-validation-for="user.Address" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.Mobile"></label>
</div>
<div class="col-6">
<input asp-for="user.Mobile" class="form-control" />
<span asp-validation-for="user.Mobile" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.PinCode"></label>
</div>
<div class="col-6">
<input asp-for="user.PinCode" class="form-control" />
<span asp-validation-for="user.PinCode" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-3 offset-4">
<input type="submit" value="Create" class="btn btn-primary
form-control" />
</div>
<div class="col-3">
<a asp-page="Index" class="btn btn-success
form-control">Back to List</a>
</div>
</div>
</form>
</div>
@section Scripts{
<partial name="_ValidationScriptsPartial" />
}
We have completed the functionality for Add the user details
Now run the application and click create new user button and add details
Step 8: Adding the functionality for Edit User
Right click on UserList folder -> Select Add option -> Select Razor Page -> Again select Razor page on top and click Add button
Give the name as Edit
Expand the Edit.cshtml and open Edit.cshtml.cs class and write below code for Edit the user details
using System.Threading.Tasks;
using CRUDExamCor.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace CRUDExamCor
{
public class EditModel : PageModel
{
private UserDBContext
_objEntity;
public EditModel(UserDBContext
objEntity)
{
_objEntity = objEntity;
}
[BindProperty]
public User user { get; set; }
public async void OnGet(int id)
{
user = await
_objEntity.users.FindAsync(id);
}
public async
Task<IActionResult> OnPost()
{
if(ModelState.IsValid)
{
var objUser = await _objEntity.users.FindAsync(user.UserId);
objUser.UserName =
user.UserName;
objUser.EmailId = user.EmailId;
objUser.Address = user.Address;
objUser.Mobile = user.Mobile;
objUser.PinCode = user.PinCode;
await
_objEntity.SaveChangesAsync();
return RedirectToPage("Index");
}
return RedirectToPage();
}
}
}
Now open Edit.cshtml and razor view code
@page
@model CRUDExamCor.EditModel
@{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<div class="border container" style="padding:30px">
<form method="post">
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<input type="hidden" asp-for="user.UserId" />
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.UserName"></label>
</div>
<div class="col-6">
<input asp-for="user.UserName" class="form-control" />
<span asp-validation-for="user.UserName" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.EmailId"></label>
</div>
<div class="col-6">
<input asp-for="user.EmailId" class="form-control" />
<span asp-validation-for="user.EmailId" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.Address"></label>
</div>
<div class="col-6">
<input asp-for="user.Address" class="form-control" />
<span asp-validation-for="user.Address" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.Mobile"></label>
</div>
<div class="col-6">
<input asp-for="user.Mobile" class="form-control" />
<span asp-validation-for="user.Mobile" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-4">
<label asp-for="user.PinCode"></label>
</div>
<div class="col-6">
<input asp-for="user.PinCode" class="form-control" />
<span asp-validation-for="user.PinCode" class="text-danger"></span>
</div>
</div>
<div class="form-group
row">
<div class="col-3 offset-4">
<input type="submit" value="Update" class="btn btn-primary
form-control" />
</div>
<div class="col-3">
<a asp-page="Index" class="btn btn-success
form-control">Back to List</a>
</div>
</div>
</form>
</div>
@section Scripts{
<partial name="_ValidationScriptsPartial" />
}
We have completed the functionality for Edit the user details
Now run the application and click Edit button and add details
So finally we have completed display,add,update and delete functionality Delete functionality code, I have already added in Index.cshtml page
Thank you and always welcome to any feedback