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

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
 
Line 49: Line 49:
  
 
We assign values to the variables we created above. Remember your database table is likely to be different and your variables should match your table and the numbers in the `reader.Get` lines should be the order of the fields in the table.
 
We assign values to the variables we created above. Remember your database table is likely to be different and your variables should match your table and the numbers in the `reader.Get` lines should be the order of the fields in the table.
 +
 +
Now in the `html` page, you need to set up your form.

Latest revision as of 09:55, 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);
    }
}

We assign values to the variables we created above. Remember your database table is likely to be different and your variables should match your table and the numbers in the `reader.Get` lines should be the order of the fields in the table.

Now in the `html` page, you need to set up your form.