(C# ASP.NET Core) Program Example on Data Display and FORM Update

(LEVEL IS BEGINNERS) Suppose there is a model called StudentData with properties ID, Name, School and Marks. Also suppose we already have a collection of StudentData records with the first three properties already filled, and Marks is NULL. Write an Index page to display the data of the students in a table of 5 columns. The fifth column contains a link button called Edit. When the link is clicked, the user should be taken to a page called Edit. The Edit page contains a form where Name and Marks can only be edited. Update the collection when the form is submited and redirect the user to the index page to show the updated record.
(Rev. 06-Nov-2022)

Categories | About |     |  

Parveen,
COMMERCIAL USE OF THIS CONTENT IS NOT ALLOWED

Create the Model Class

First of all create a simple ASP.NET Core Project and add a folder called Models, and then a class called StudentData to this folder.


// the completed project is attached to 
// the downloads of this tutorial 

// model class 

namespace MyFirstApp.Models
{
  public record class StudentData(int ID, 
                                  string Name, 
                                  string School, 
                                  int? Marks)
  {
    public static IList<StudentData> GetSeedData() 
      => new List<StudentData>() 
      {

        new(1, "Garry Holmes", "MIT", null), 
        new(2, "James Smith", "MIT", null)

      };

  }

}

We have added a record class StudentData with all the required properties. This class also contains a static function to provide two items with ID, Name and School already filled, and the fourth property for Marks is null.

Video Explanation (see it happen!)

Please watch the following youtube video:

Program.cs File

Next let us examine the Program.cs file.


// program.cs 

using MyFirstApp.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services
       .AddSingleton<IList<StudentData>> 
                    (p => StudentData.GetSeedData());

var app = builder.Build();

app.UseRouting();

app.MapRazorPages();

app.Run();

The first two lines are the usual boilerplate code that must already be familiar with.

After this we have added the list of students to the dependency container. ASP.NET Core will make it available to the razor pages through a constructor. The concept of dependency injection has been explained in the chapters of database connectivity. The basic point is that we have made an arrangement of using a collection as a data source.

The remaining lines of this file are again the usual boiler plate.

Index Home Page File

Next let's come to the index home page.

The @inject directive provides us the collection of StudentData records that we added to the services container in the program.cs file.

After this we have added a table for displaying the data.


// see the video for screenshots 

@page 

@inject IList<StudentData>? _students

<h1>Data of Students</h1>

<table border="1">

  <tr>
    <th>ID</th><th>School</th><th>Name</th><th>Marks</th><th></th>
  </tr>

  @foreach (var student in Model._students!)
  {
    <tr>
      <td>
        @student.ID
      </td>
      <td>
        @student.School
      </td>
      <td>
        @student.Name
      </td>
      <td>
        @student.Marks 
      </td>
      <td>
        <a asp-page="Edit" asp-route-id=@student.ID>Edit</a>
      </td>
    </tr>
  }

</table>


  

And we can scroll further to the for-each loop that generates the rows of the table.

The fifth column contains an anchor that sends the id of the record to the Edit.cshtml page.

You can obtain the source code from the downloads of this course.

Edit Page

Next let's come to the Edit.cshtml file.

We have written the entire code in this single file. We have also kept it simple by avoiding error and null checks that should always be done in a professional application.

The @inject directive provides the list of records.

@page "{id:int?}"

@inject IList<StudentData>? _students

@functions {

  // KEPT SIMPLE FOR TUTORIAL 
  // ERROR/NULL CHECKS NOT DONE 

  [BindProperty]
  public StudentData? Student { get; set; }

  public void OnGet(int? id)
  {
    Student = _students?.FirstOrDefault(s => s.ID == id);
  }

  public IActionResult OnPost()
  {
    // the POSTED data is in the BindProperty Student 

    // locate and update the collection 
    for (int x = 0; x < _students!.Count; x++)
    {
      if (_students[x].ID == Student!.ID)
      {
        _students[x] = Student;

        break;
      }
    }

    return RedirectToPage("Index");
  }
}


<h1>Update Record</h1>

<table>

  <form method="post">

  <tr>

    <td>
      <label asp-for="Student!.Name"></label>
    </td>

    <td>
      <input asp-for="Student!.Name" type="text" />
    </td>

  </tr>

  <tr>

    <td>
      <label asp-for="Student!.Marks"></label>
    </td>

    <td>
      <input asp-for="Student!.Marks" type="number" />
    </td>

  </tr>

  <tr>

    <td colspan="2">

    // IMPORTANT: ALL the fields of the BindProperty 
    // have to be set, otherwise they will reach 
    // as 0 or NULL  

      <input asp-for="Student!.ID" type="hidden" />
      <input asp-for="Student!.School" type="hidden" />

      <input type="submit" />

    </td>

  </tr>

  </form>

</table>

  

Then we have a BindProperty for the form.

The OnGet function obtains the student record from _students.

The OnPost method saves the posted Student record into the list of students and redirects to the index home page.

Next let's have a look at the form. We have used a table to present a textbox for student's name. The BindProperty brings the existing data and ensures that the textbox shows the name of the student. We can scroll further to see a text box for marks.

Scrolling further down we have used two hidden fields for the other two properties - ID and School. If we do not use these hidden fields then the OnPost method will not receive these in the bind property. The bindproperty must be fully set in the form before it is posted.

You can run the project to verify that it works as expected. Thanks!


This Blog Post/Article "(C# ASP.NET Core) Program Example on Data Display and FORM Update" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.