Difference between revisions of "Create a edit page for ASP.Net Web App"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "Create a new `razor` page to edit entries stored in a specific database table, ie Customers, Products and so on. Inside the Model (ie .cs file) create a variable to store eac...")
 
Line 9: Line 9:
 
string Address="";
 
string Address="";
 
string TelNo="";
 
string TelNo="";
 +
</syntaxhighlight>
 +
 +
Now in the `OnGet` method create a MySQL database connection:
 +
 +
<syntaxhighlight lang=csharp>
 +
public void OnGet()
 +
{
 +
    using var connection = GetConnection; // this gets the connection
 +
 +
    connection.Open(); // you must open the connection
 +
           
 +
    connection.Close();
 +
}
 +
</syntaxhighlight>
 +
 +
Now between the `connection.Open()` and the `connection.Close()` create the command and SQL to retrieve the record you want to edit:
 +
 +
<syntaxhighlight lang=csharp>
 +
using var Command = new MySqlCommand("SELECT * FROM Customer where ID=@id", connection);
 +
Command.Parameters.AddWithValue("@id", id);
 +
using var reader = Command.ExecuteReader();
 +
 +
</syntaxhighlight>
 +
Now, after you have created the reader and executed it we need to check if it has selected anything:
 +
 +
<syntaxhighlight lang=csharp>
 +
if(reader.HasRows)
 +
{
 +
    while(reader.Read())
 +
    {
 +
        ID = reader.GetInt32(0);
 +
        Name = reader.GetString(1);
 +
        Email = reader.GetString(2);
 +
        Address = reader.GetString(3);
 +
        TelNo = reader.GetString(4);
 +
    }
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 09:43, 18 December 2024

Create a new `razor` page to edit entries stored in a specific database table, ie Customers, Products and so on.

Inside the Model (ie .cs file) create a variable to store each field:

int ID = -1;
string Name="";
string Email="";
string Address="";
string TelNo="";

Now in the `OnGet` method create a MySQL database connection:

public void OnGet()
{
    using var connection = GetConnection; // this gets the connection

    connection.Open(); // you must open the connection
            
    connection.Close();
}

Now between the `connection.Open()` and the `connection.Close()` create the command and SQL to retrieve the record you want to edit:

using var Command = new MySqlCommand("SELECT * FROM Customer where ID=@id", connection);
Command.Parameters.AddWithValue("@id", id);
using var reader = Command.ExecuteReader();

Now, after you have created the reader and executed it we need to check if it has selected anything:

if(reader.HasRows)
{
    while(reader.Read())
    {
        ID = reader.GetInt32(0);
        Name = reader.GetString(1);
        Email = reader.GetString(2);
        Address = reader.GetString(3);
        TelNo = reader.GetString(4);
    }
}