A simple example of returning a partial ActionResult in a Razor Page

Returning a partial ActionResult allows us to update content on a page without reloading the page. This simple example lists some students and allows us to display detail about a student with a click. We use entity framework and .net core.

In this example, the students are listed with a button next to each student. The button is clicked to insert detail on the student at the top of the page. The page is not reloaded. Only the detail is changed.

The click triggers some Javascript with a fetch to a Task – OnGetDetailAsync using the handler query. This Task pulls the student and returns the Partial action class. The first parameter is the name of the partial view. The second parameter is the model – Student.

The Partial returns the detail which is then picked up by the fetch and used to replace the HTML of the “details” div.

Details on setting up a .net core application and connecting the database to the app are omitted here.

Create database table, model, and context class

Create a table in a database called Students with fields ID, FirstName, LastName, and Detail. Then, in your code, generate a model for this table.

...
using System.ComponentModel.DataAnnotations;

namespace Users.Models
{
    public class Student
    {
        [Key]
        public int ID { get; set; }

        [StringLength(50)]
        public string FirstName { get; set; }

        [StringLength(50)]
        public string LastName { get; set; }

        [StringLength(450)]
        public string Detail { get; set; }
    }
}

Add the Users Context class.

using Microsoft.EntityFrameworkCore;
using Users.Models;

namespace Users.Data
{
    public class UsersContext : DbContext
    {
        public UsersContext (DbContextOptions<UsersContext> options)
            : base(options)
        {
        }
        public DbSet<Users.Models.Student> Students { get; set; }
    }
}

Create the Razor page

Add a Razor Page that includes the following code.

@page
@model Users.Pages.ViewStudentsModel
...
    <div id="details" 
         style="border-color:red; border-style:double; display:none; margin-top:10px; margin-bottom:10px;padding:10px;"
         ></div>

    <table class="table">
        <tbody>
            @foreach (var item in Model.Students)
            {
                <tr>
                    <td>
                        @item.ID
                    </td>
                    <td>
                        @item.FirstName
                    </td>
                    <td>
                        @item.LastName
                    </td>
                    <td>
                        <button onclick="handleClick(@item.ID)">Get Detail</button>
                    </td>

                </tr>
            }
        </tbody>
    </table>
...

Add a script for the onclick event and place in the Razor Page.

<script>
  
    function handleClick(id) {
        console.log("did click" );
        var url = window.location.href;
        fetch(url + '?handler=Detail&id=' + id)
            .then(response => response.text())
            .then((data) => {
                var details = document.getElementById("details");
                details.innerHTML = data;
                details.style.display="block";
            });   
    }
</script>

Create the code behind for the Razor Page.

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

namespace Users.Pages
{
    public class ViewStudentsModel : PageModel
    {
        private readonly Users.Data.UsersContext _context;

        public ViewStudentsModel(Users.Data.UsersContext context)
        {
            _context = context;
        }

        public IList<Student> Students { get;set; }
        public Student Student { get; set; }

        public async Task<IActionResult> OnGetAsync()
        {
         
            Students = await _context.Students.ToListAsync();
            return Page();

        }
        public async Task<IActionResult> OnGetDetailAsync(int? id)
        {

            Student = await _context.Students.FirstOrDefaultAsync(m => m.ID == id);
            return Partial("_PartialStudent", Student);

        }
    }
}

Add the partial page

Finally add the partial class file called _PartialStudent.

@model Users.Models.Student

<div>  @Model.Detail</div>

Leave a Reply

Your email address will not be published. Required fields are marked *