Friday, July 21, 2023

ASP.NET Core Razor Pages CRUD operation Example



Project
  • Open the Visual Studio. 
  • Create web project using ASP.NET Core Empty template.
  • Project name: RPExercises
  • Solution name: RPExercises
  • .NET Core version: 5.0
  • Create Models folder and Student class in it.
Model class: The Student model class is as follows.

namespace RPExercises.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public int? Marks { get; set; }
    }
}
Packages: Install the NuGet packages using following commands
  • Install-Package Microsoft.EntityFrameworkCore -Version 5.0
  • Install-Package Microsoft.EntityFrameworkCore.Tools -Version 5.0
  • Install-Package Microsoft.EntityFrameworkCore.Design -Version 5.0
  • Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0
AppDbContext: Create Data folder and AppDbContext class in it. This class derives from DbContext class.

using Microsoft.EntityFrameworkCore;
using RPExercises.Models;

namespace RPExercises.Data
{
    public class AppDbContext: DbContext
    {
        public AppDbContext(DbContextOptions options)
       : base(options)
        {
        }
        public DbSet tblStudents { get; set; }
    }
}
Update the appsettings file for connection string.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DBCS": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Appliedk9;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
  },
  "AllowedHosts": "*"
}
Update Startup class.
Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RPExercises.Data;

namespace RPExercises
{
    public class Startup
    {
        private readonly IConfiguration _cfg;

        public Startup(IConfiguration configuration)
        {
            _cfg = configuration;
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddDbContext<AppDbContext>(options =>
            {
                options.UseSqlServer(_cfg.GetConnectionString("DBCS"));
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}
Run the following commands in Package Manager Console. 
  • Add-Migration Initial 
  • Update-Database
  • Add a New Folder and rename it Pages.
  • Add a Razor Page in Pages folder and name it Index. Two files are generated which are Index.cshtml and Index.cshtml.cs
The Project folders will be as depicted below.


Next step. Update the Index.cshtml to get the list of students from tblStudents table.

Next step. Update the Index.cshtml to create a list of students.
Index.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RPExercises.Data;
using RPExercises.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RPExercises.Pages
{
    public class IndexModel : PageModel
    {
        public List<Student> students { get; set; } = new List<Student>();
        private readonly AppDbContext ctx;

        public IndexModel(AppDbContext ctx)
        {
            this.ctx = ctx;
        }
        public async Task<IActionResult> OnGet()
        {
            students = await ctx.tblStudents.ToListAsync();
            return Page();
        }
    }
}
Index.cshtml

@page
@model RPExercises.Pages.IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h2>List students</h2>
<br/>
<form method="get">
    <table border="1" cellpadding="4">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Sex</th>
            <th>Marks</th>
            <th>Edit</th>
        </tr>
        @if (Model.OnGet()!=null)
        {
            @foreach (var student in Model.students)
            {
                <tr>
                    <td>@student.Id</td>
                    <td>@student.Name</td>
                    <td>@student.Sex</td>
                    <td>@student.Marks</td>
                    <td><a asp-page="Edit" asp-route-id="@student.Id">Edit</a></td>
                </tr>
            }
        }
        
    </table>
</form>
<h3><a asp-page="Create">Create</a></h3> 
Create Page. Create Create razor page. Add the following code. 

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RPExercises.Data;
using RPExercises.Models;
using System;
using System.Threading.Tasks;

namespace RPExercises.Pages
{
    public class CreateModel : PageModel
    {
        private readonly AppDbContext ctx;

        public CreateModel(AppDbContext ctx)
        {
            this.ctx = ctx;
        }
        [BindProperty]
        public Student Student { get; set; }
        public IActionResult OnGet()
        {
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            Student s1 = new Student();
            s1.Id = Convert.ToInt32(Request.Form["Id"]);
            s1.Name = Request.Form["Name"];
            s1.Sex = Request.Form["Sex"];
            s1.Marks = Convert.ToInt32(Request.Form["Marks"]);
            await ctx.tblStudents.AddAsync(Student);
            await ctx.SaveChangesAsync();
            return RedirectToPage("Index");
        }
    }
}
CreateModel

@page
@model RPExercises.Pages.CreateModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h1>Create student</h1>
<form method="post">
    <table border="1" cellpadding="4">
        <tr hidden>
            <td hidden><label asp-for="Student.Id"></label></td>
            <td hidden><input asp-for="Student.Id" /></td>
        </tr>
        <tr>
            <td><label asp-for="Student.Name"></label></td>
            <td><input asp-for="Student.Name" /></td>
        </tr>
        <tr>
            <td><label asp-for="Student.Sex"></label></td>
            <td><input asp-for="Student.Sex" /></td>
        </tr>
        <tr>
            <td><label asp-for="Student.Marks"></label></td>
            <td><input asp-for="Student.Marks" /></td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:right;"><input type="submit" /></td>
        </tr>
    </table>
</form>

Run the application. We get the following form. Initially, there will be no record.

Click Create link to open another form to create a student record. Fill the data and click Submit button.

No comments:

Post a Comment

Hot Topics