To post data into a database using forms in ASP.NET, you typically use the POST method to submit the form data to the server. Here's a general outline of how to do this:
- Create an HTML Form: Set up an HTML form that collects the data you want to send to the server. For example:
<form method="post" action="/submit"> <input type="text" name="username" placeholder="Username" /> <input type="password" name="password" placeholder="Password" /> <input type="email" name="email" placeholder="Email" /> <input type="text" name="pass_code" placeholder="Pass Code" /> <input type="submit" value="Submit" /> </form> - Handle the POST Request: In your server-side code (e.g., in a Razor page), check if the request is a
POSTrequest. If it is, retrieve the form values usingRequest.Formand insert them into the database:@if (IsPost) { var username = Request.Form["username"]; var password = Request.Form["password"]; var email = Request.Form["email"]; var passCode = Request.Form["pass_code"]; var db = Database.Open("YourDatabaseName"); var insertCommand = "INSERT INTO Users (Username, Password, Email, Pass_Code) VALUES(@0, @1, @2, @3)"; db.Execute(insertCommand, username, password, email, passCode); Response.Redirect("/success"); // Redirect after successful submission } - Display Data: To retrieve and display data from the database, you can use a
GETrequest. For example, you might have another page that queries the database and displays the information:var db = Database.Open("YourDatabaseName"); var results = db.Query("SELECT * FROM Users"); foreach (var row in results) { <p>@row.Username - @row.Email</p> }
In your VB.NET code, you would need to adjust the syntax accordingly, but the principles remain the same: use POST for submitting data and GET for retrieving data. Make sure to handle the database connection and queries properly to avoid SQL injection by using parameterized queries as shown above.
References: