Modifying Data  «Prev  Next»

Lesson 1

Modifying Data Using Web Programming

Data in the VirtualBookShelf database doesn't sit still. Books arrive and sell through, quantities on hand rise and fall, prices change, and customers sign up, update their details, or leave. Every previous module in this course assumed the data was already there and simply read it; this module builds the web pages that actually change it.

The original version of this course taught the same idea using Visual InterDev's data-bound Design Time Controls and classic ADO's Recordset object, whose AddNew, Update, and Delete methods did the actual work of changing a row once a visitor filled in a form. This module replaces that layer the same way Module 4 replaced Recordset and Command for reading data: with ADO.NET, running inside an ASP.NET Core Razor Pages application built on .NET 10, talking to SQL Server 2025. Across the lessons ahead, this module covers:
  1. Adding an Update button that changes an existing row
  2. Adding an Insert button that adds a new row
  3. Adding a Delete button that removes a row
Dragging a Recordset DTC onto a page and binding a Grid or form controls next to it was quick, and the convenience was real. It's also gone; nothing in Visual Studio 2026 drags a data-bound control onto a Razor Page. What replaces it is a small, consistent pattern built directly on top of what Module 4 already established, covered one operation at a time rather than all three at once.

How a Razor Page Actually Changes Data

Module 4 showed that a Razor Page is backed by a page model class, a C# class that prepares whatever a page needs. Reading data used OnGet, the method a page runs automatically on an ordinary request. Changing data uses a different kind of method, one tied to a specific form submission rather than to the page loading.

A Razor Page can define more than one of these submission handlers, one for each action a visitor might take, and tell its markup which handler a given form or button should call using the asp-page-handler Tag Helper introduced in Module 4. At a preview level, without full working code yet, the shape looks like this:

public class InventoryModel : PageModel
{
    public async Task<IActionResult> OnPostUpdateAsync(int bookId, decimal newPrice)
    {
        // Runs the UPDATE statement, covered in this
        // module's second lesson.
        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostInsertAsync(Book newBook)
    {
        // Runs the INSERT statement, covered next.
        return RedirectToPage();
    }

    public async Task<IActionResult> OnPostDeleteAsync(int bookId)
    {
        // Runs the DELETE statement, covered last.
        return RedirectToPage();
    }
}
and a form in the page's markup points at one of them by name:

<form method="post" asp-page-handler="Update">
    <input type="hidden" asp-for="BookId" />
    <input type="number" asp-for="NewPrice" />
    <button type="submit">Update Price</button>
</form>
Nothing here is dragged onto a design surface, and nothing stays silently bound to a live database row the way a Recordset DTC once did. A visitor submits a form, ASP.NET Core routes that submission to the matching OnPost<Name>Async method by its handler name, and that method decides exactly what SQL runs, if any. This module's three lessons fill in the SQL each of the three methods above still leaves as a comment.

What ADO.NET Replaces: AddNew, Update, and Delete

Classic ADO's Recordset object exposed its own update, insert, and delete behavior directly as methods, called against a row the Recordset was already positioned on:

' Classic ADO, shown for comparison only. Not used in this course.
oRS.AddNew
oRS("Title") = "New Title"
oRS("Price") = 24.99
oRS.Update

oRS("Price") = 19.99
oRS.Update

oRS.Delete
This worked because a Recordset, in its default mode, stayed connected to the database and tracked which row was current. ADO.NET has no equivalent object to stay positioned on a row, and doesn't need one, because a Razor Page's model binding already knows which row a visitor is acting on: it arrives as a parameter, such as bookId in the handler sketch above, pulled directly from the submitted form.

In place of AddNew, Update, and Delete as Recordset methods, this module uses a single ADO.NET object for all three: SqlCommand, the same class Module 4 used for SELECT statements, now holding an INSERT, UPDATE, or DELETE statement instead. What changes isn't the object, it's which method runs it and what the SQL text says.

There's a second difference worth naming directly. A Recordset's AddNew and Update methods worked against an in-memory copy of a row, column by column, and only sent that row to the database once Update was actually called; a developer could set several columns and only commit them all together. A SqlCommand running an INSERT or UPDATE has no such staging step. Its SQL text names every column and value the statement needs up front, and the entire statement runs as one unit the moment ExecuteNonQueryAsync is called. That's not a limitation so much as a simplification: there's one fewer object to track, and one fewer place for a half-finished change to be left sitting in memory if something goes wrong partway through.

Executing a Change Instead of Reading One

Module 4's queries called ExecuteReader, because a SELECT statement returns rows that need reading. An INSERT, UPDATE, or DELETE statement doesn't return rows at all, so SqlCommand offers a different method for them: ExecuteNonQueryAsync, the asynchronous form of the same ExecuteNonQuery method this course's third module already named when Lesson 3 ran its first UPDATE statement directly in Azure Data Studio. Where ExecuteReader hands back a SqlDataReader to step through, ExecuteNonQueryAsync hands back a single integer: the number of rows the statement actually changed.

SqlCommand command = new(
    "UPDATE Inventory SET Price = @NewPrice WHERE BookID = @BookID",
    connection);
command.Parameters.AddWithValue("@NewPrice", newPrice);
command.Parameters.AddWithValue("@BookID", bookId);

int rowsAffected = await command.ExecuteNonQueryAsync();
That returned count is worth checking, not discarding. If rowsAffected comes back as zero, nothing matched the WHERE clause, which usually means the BookID a visitor submitted no longer exists, perhaps because another visitor deleted that same row moments earlier. A page model that ignores this return value has no way to tell the difference between "the update succeeded" and "the update quietly did nothing," a distinction this module's hands-on lessons build into every handler from the first working example onward.

Three Operations, One Shared Habit: Test the SQL First

Module 4 established the habit of writing and confirming a query in Azure Data Studio before moving it into a SqlCommand, and nothing about that habit changes just because this module's statements modify data instead of reading it. If anything, it matters more here: running a malformed SELECT against the wrong table returns an empty or confusing result, but running a malformed DELETE against the wrong table, or one missing its WHERE clause entirely, removes rows that are gone the moment the statement commits. Confirming each INSERT, UPDATE, and DELETE against VirtualBookShelf's actual Inventory or Customer table, with real sample rows, before it's ever wrapped in a SqlCommand, catches exactly the kind of mistake that's expensive to catch any later.

Parameterized Queries Still Matter Here

Module 4 built every filtered SELECT around a parameterized SqlCommand rather than pasting a visitor-supplied value directly into SQL text, because the risk that guards against, SQL injection, has nothing to do with whether a statement happens to read data or change it. If anything, the stakes are higher for this module's statements: a successful injection against a SELECT exposes data a visitor shouldn't see, but a successful injection against an UPDATE or DELETE can change or remove data that shouldn't have been touched at all.

The unsafe shape is the same one Module 4 already warned against, just with a different verb:

string unsafeSql = "DELETE FROM Inventory WHERE BookID = " + bookId;
If bookId comes from a form field a visitor can edit before submitting, a value like 1 OR 1=1 turns one intended deletion into every row in the table. Every SqlCommand this module builds keeps the value separate from the SQL text instead, exactly as shown in the UPDATE example above, with @BookID standing in as a placeholder and AddWithValue supplying the actual number. This isn't a new rule for this module to learn; it's the same rule Module 4 already established, applied without exception to statements that write instead of read.

What This Module Doesn't Need

Some of the material this lesson's own research touched on belongs to a different course entirely. A WinForms or WPF desktop application, bound to a dataset through a DataGridView and a TableAdapter Configuration Wizard, is a genuinely different kind of application from the Razor Pages web application this course has built since Module 1, with its own project type, its own designer surfaces, and no overlap with anything covered here. The same is true of ASP.NET Web Forms, a SqlDataSource control bound to a GridView with AutoGenerateEditButton="True": real, but a different framework with a different programming model, retired in favor of ASP.NET Core years before this course's current edition.

Entity Framework Core is a closer call, since it's a real part of this course's future and a genuinely common way to modify data in a modern .NET application. It's still not this module's tool. EF Core wraps a DbContext and SaveChangesAsync around work that, underneath, still opens a connection and runs SQL; this module builds that underlying layer by hand first, with SqlCommand and ExecuteNonQueryAsync, the same choice Module 4 made for reading data and for the same reason. Once a developer has written an UPDATE or a DELETE by hand and watched exactly what it does, EF Core's automatic version is far less mysterious whenever this course gets there.

The same caution applies to a SQL Server Management Studio shortcut worth knowing about but not relying on here: right-clicking a table and choosing to edit its top rows directly in a grid. That's a genuinely fast way for a developer to fix a handful of rows by hand while working inside SSMS itself, but it has nothing to do with how a visitor to a web page changes data, since a visitor never has SSMS open at all. This module's Update, Insert, and Delete buttons are the equivalent a visitor actually gets, built entirely in the application rather than in a database administration tool.

Module Objectives

With the legacy Recordset DTC's three data-changing methods replaced piece by piece above, this module's three objectives are:
  1. Add an Update button that changes an existing row in VirtualBookShelf's Inventory or Customer table using a parameterized SqlCommand.
  2. Add an Insert button that adds a new row to one of those tables the same way.
  3. Add a Delete button that removes a row, with the same parameterization and the same attention to how many rows a statement actually affects.
Each objective maps directly onto one of classic ADO's Recordset methods, AddNew, Update, and Delete, and onto one of the three handler methods sketched earlier in this lesson, just built with SqlCommand and ExecuteNonQueryAsync instead of a bound control's property sheet.

Frequently Asked Questions

Why does ExecuteNonQueryAsync return an integer instead of nothing at all? Because that integer is the only confirmation a page model gets that a statement actually did what it was supposed to. A method with no return value at all would leave no way to distinguish a successful update from one whose WHERE clause matched zero rows, which is exactly the distinction this lesson's rowsAffected check exists to catch.

Is ExecuteNonQueryAsync only for INSERT, UPDATE, and DELETE? Those three are the common case, but anything that isn't a row-returning query uses it, including statements like CREATE TABLE or CREATE INDEX. This module only needs it for the three data-changing statements named above.

Do these new handler methods replace OnGet from Module 4? No. A Razor Page typically keeps its OnGet method for the initial display of its data and adds separate OnPost<Name>Async methods alongside it for each action a form on that page can trigger. A single page can display VirtualBookShelf's inventory through OnGet and also offer an Update button and a Delete button next to each row, each wired to its own handler.

What happens if two visitors try to update the same row at nearly the same time? SQL Server 2025's Optimized Locking, covered at an overview level in an earlier module, reduces how long a row stays locked during a short update like this one, but it doesn't eliminate the underlying possibility that two updates can still arrive close together. This module's lessons don't build explicit conflict detection, such as checking whether a row changed since it was last read, that's a more advanced topic than a first working Update button needs, but it's worth knowing the possibility exists.

Could the same SqlCommand be reused for the Insert, Update, and Delete handlers? Not the same command instance with the same SQL text, since each operation runs a different statement, but the pattern connecting, building a command, adding parameters, calling ExecuteNonQueryAsync, repeats identically across all three. Once OnPostUpdateAsync is written, OnPostInsertAsync and OnPostDeleteAsync largely follow the same shape with a different SQL statement and a different set of parameters.

Does a DELETE statement need parameters the same way an UPDATE does? Yes, every bit as much. A DELETE without a parameterized WHERE clause is exactly as vulnerable to the SQL injection risk described earlier as an unparameterized UPDATE, and arguably more dangerous, since a successful injection removes data rather than merely exposing or changing it.

What should happen if ExecuteNonQueryAsync throws an exception, say because a DELETE violates a foreign key constraint? The same structured exception handling Module 4 introduced applies here without modification: a try block around the ADO.NET call, a catch (SqlException ex) block that logs the error and shows the visitor a plain message instead of a raw stack trace. This module's lessons build that habit in from the first working handler, rather than adding it as an afterthought.

Why use a button with asp-page-handler instead of a separate page for each operation? Keeping Update, Insert, and Delete as handlers on the same page, next to the data they affect, mirrors how the original Recordset DTC and its bound controls sat together on one page; splitting each action onto its own separate page would work but scatters related functionality that's easier to read, and easier to maintain, kept together.

Is there a modern equivalent to validating a visitor's input before it reaches the database, the way a DTC's property sheet might have offered field-level validation? Yes. ASP.NET Core supports data annotation attributes, such as [Required] or [Range], placed directly on a model's properties, checked automatically before a handler method's body even runs. This module's lessons touch on basic parameter checks; full model validation is a natural extension once the three core operations are working.

What's Ahead

This lesson stayed at the preview level on purpose, naming SqlCommand and ExecuteNonQueryAsync as the pair that replaces AddNew, Update, and Delete, and sketching three handler methods without yet writing a complete, working version of any of them. The next three lessons build those versions one at a time, in the order this lesson's objectives listed them: first an Update button that changes an existing row, then an Insert button that adds a new one, and finally a Delete button that removes one.

Each of those lessons reuses exactly what Module 4 already built: a connection string read from appsettings.json, a SqlConnection opened the same way, and parameterized SqlCommand objects built with the same discipline. Only the SQL statement and the ADO.NET method that runs it change from one lesson to the next. By the end of this module, a visitor to a VirtualBookShelf page will be able to do everything the original Recordset DTC's bound controls once did, update a price, add a new title, remove a row, with every statement tested first in Azure Data Studio and every value supplied by a visitor passed through a parameter, never pasted into SQL text.

SEMrush Software 1 SEMrush Banner 1