In this article I will explain with an example, how to update Database Table using ListBox in ASP.Net Core (.Net Core) Razor Pages.
Note: For beginners in ASP.Net Core (.Net Core 7) Razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

Database

I have made use of the following table Hobbies with the schema as follow.
ASP.Net Core Razor Pages: Update Database Table using ListBox
 
I have already inserted few records in the table.
ASP.Net Core Razor Pages: Update Database Table using ListBox
 
Note: You can download the database table SQL by clicking the download link below.
            Download SQL file
 
 

Model

The following two Models are created.

HobbyModel

public class HobbyModel
{
    [Key]
    public int HobbyId { getset; }
    public string Hobby { getset; }
    public bool IsSelected { getset; }
}
 

Hobby

public class Hobby
{
    public List<SelectListItem> Hobbies { getset; }
    public List<string> HobbyIds { getset; }
}
 
 

Database Context

Once the Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
Note: For beginners in ASP.Net Core (.Net Core 7) Razor Pages and Entity Framework, please refer my article .Net Core 7: Entity Framework Tutorial in ASP.Net Core Razor Pages. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core (.Net Core 7) Razor Pages.
 
using Microsoft.EntityFrameworkCore;
 
namespace ListBox_Update_DB_Core_Razor
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<HobbyModel> Hobbies { getset; }
    }
}
 
 

PageModel (Code-Behind)

The PageModel consist of following Handler methods.

Handler method for handling GET operation

Inside this Handler method, an object of Hobby class is created and its Hobbies property is set with the Generic List collection i.e. records of the Hobbies Table which is returned from the PopulateHobbies method (explained later).
 

PopulateHobbies

Inside this method, the records are fetched from the Hobbies Table using Entity Framework and added to the Generic List collection of SelectListItem class which is finally returned.
 

Handler method for handling POST operation

This Handler method gets called when Submit Button is clicked which accepts HobbyModel class object as a parameter.
Inside this Handler method, first the Hobbies property of HobbyModel class is set with the records returned from the PopulateHobbies method (explained earlier).
Then, a check is performed if the HobbyIds property is NULL or not, if not NULL then a FOR EACH loop is executed over the Generic List collection of Hobbies.
Inside the loop, the UpdateHobby method (explained later) is called which accepts the value i.e. HobbyId and the status of that Hobby whether it is selected or not.
Note: The status is determined based on the presence of that HobbyId in the Generic List collection of string created earlier in the HobbyModel class.
 
Finally, the success message is set into a ViewData object and the object of HobbyModel class is returned to the View.
 

UpdateHobby

Inside this method, a check is performed whether the HobbyId of the current item of the ListBox is present in the HobbyId i.e. Model property and if found then IsSeletced property is set based on the value accepted as parameter.
Finally, the SaveChanges method of DbContext is called which updates the records in the Database Table.
public class IndexModel : PageModel
{
    private DBCtx Context { get; }
    public IndexModel(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public Hobby Hobby { getset; }
 
    public void OnGet()
    {
        this.Hobby = new Hobby();
        this.Hobby.Hobbies = this.PopulateHobbies();
    }
 
    public void OnPostSubmit(Hobby hobby)
    {
        this.Hobby = new Hobby();
        this.Hobby.Hobbies = this.PopulateHobbies();
        if (hobby.HobbyIds != null)
        {
            foreach (SelectListItem item in this.Hobby.Hobbies)
            {
                this.UpdateHobby(int.Parse(item.Value), hobby.HobbyIds.Contains(item.Value));
            }
 
            ViewData["Message"] = "Records successfully updated!";
        }
    }
 
    private void UpdateHobby(int hobbyIdbool isSelected)
    {
        HobbyModel hobby = (from h in this.Context.Hobbies
                            where h.HobbyId == hobbyId
                            select h).FirstOrDefault();
 
        hobby.IsSelected isSelected;
        this.Context.SaveChanges();
    }
 
    private List<SelectListItem>PopulateHobbies()
    {
        List<SelectListItem> hobbies = (from hobby in this.Context.Hobbies
                                        select new SelectListItem
                                        {
                                            Text = hobby.Hobby,
                                             Value = hobby.HobbyId.ToString()
                                        }).ToList();
        return hobbies;
    }
}
 
 

Razor Page (HTML)

Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The Razor Page consists of a Form inside which an HTML INPUT SELECT element is used which has been assigned with the multiple property set to multiple that makes it a ListBox element.
The ListBox has been also assigned with the model property.
The Razor Page also consists of a Submit Button which has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
 

Submitting the Form

When the Submit Button is clicked then, the ViewData object is checked for NULL and if it is not NULL then, the value of the ViewData object is displayed using JavaScript Alert Message Box.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model ListBox_Update_DB_Core_Razor.Pages.IndexModel
@{
     Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post">
        Hobbies:
        <br /><br />
        select id="lstHobbies" asp-items="Model.Hobby.Hobbies" multiple="multiple" name="HobbyIds"> 
        </select>
        <br /><br />
        <input type="submit" value="Save" asp-page-handler="Submit" />
    </form>
    @if (ViewData["Message"] != null)
    {
        <script type="text/javascript">
             window.onload = function () {
                alert("@ViewData["Message"]");
            };
        </script>
    }
</body>
</html>
 
 

Screenshots

Form

ASP.Net Core Razor Pages: Update Database Table using ListBox
 

Record before Updating

ASP.Net Core Razor Pages: Update Database Table using ListBox
 

Records after Updating

ASP.Net Core Razor Pages: Update Database Table using ListBox
 
 

Downloads