WebPages Forms
Forms are essential in web applications for collecting user input. ASP.NET WebPages makes it easy to create and handle forms using Razor syntax and server-side processing.
Key Topics
Creating Forms
Example
<form method="post" action="/SubmitForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
<button type="submit">Submit</button>
</form>
Explanation: This example demonstrates a basic HTML form with input fields for name and email. The method="post"
attribute specifies that the data will be sent to the server using the POST method.
Additional Example
@{
if (IsPost)
{
var name = Request["name"];
var email = Request["email"];
}
}
<h2>Submit Your Details</h2>
<form method="post">
<input type="text" name="name" placeholder="Your Name" />
<input type="email" name="email" placeholder="Your Email" />
<button type="submit">Send</button>
</form>
Explanation: This example uses Razor to handle form submission. The Request
object retrieves the form data on the server side.
Form Validation
Example
@{
if (IsPost)
{
var name = Request["name"];
var email = Request["email"];
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email))
{
Response.Write("Please fill all fields.");
}
}
}
<form method="post">
<input type="text" name="name" placeholder="Name" />
<input type="email" name="email" placeholder="Email" />
<button type="submit">Submit</button>
</form>
Explanation: This example includes simple validation logic that checks if the name or email fields are empty and displays a message if they are.
Key Takeaways
- Forms are used to collect user input and send it to the server for processing.
- ASP.NET WebPages provides easy handling of form data through Razor syntax.
- Validation can be implemented to ensure that user input is complete and valid.