
Webpages Forms in ASP
Absolutely! Here’s a straightforward guide on handling forms in ASP.NET Web Pages (WebMatrix) — covering form creation, submission, retrieving data, validation, and more.
Working with Forms in ASP.NET Web Pages
1. Creating a Basic HTML Form
<form method="post"> Name: <input type="text" name="name" /> Email: <input type="email" name="email" /> <input type="submit" value="Submit" /></form>
2. Handling Form Submission and Retrieving Data
@{ if (IsPost) { var name = Request.Form["name"]; var email = Request.Form["email"]; }}
3. Display Submitted Data
@if (IsPost) { <p>You submitted: Name = @Request.Form["name"], Email = @Request.Form["email"]</p>}
4. Simple Validation Example
@{ var error = ""; if (IsPost) { var name = Request.Form["name"]; var email = Request.Form["email"]; if (String.IsNullOrWhiteSpace(name) || String.IsNullOrWhiteSpace(email)) { error = "Both Name and Email are required."; } else { <p>Thank you, @name!</p>; } }}<form method="post"> Name: <input type="text" name="name" value="@Request.Form["name"]" /> Email: <input type="email" name="email" value="@Request.Form["email"]" /> <input type="submit" value="Submit" /></form>@if (!String.IsNullOrEmpty(error)) { <p style="color:red;">@error</p>}
5. Using Request.QueryString
for GET Forms
@{ var search = Request.QueryString["search"];}<form method="get"> Search: <input type="text" name="search" value="@search" /> <input type="submit" value="Search" /></form>@if (!String.IsNullOrEmpty(search)) { <p>You searched for: @search</p>}
6. File Upload Form
<form method="post" enctype="multipart/form-data"> Select file: <input type="file" name="fileUpload" /> <input type="submit" value="Upload" /></form>@{ if (IsPost) { var file = Request.Files["fileUpload"]; if (file != null && file.ContentLength > 0) { var savePath = Server.MapPath("~/uploads/" + file.FileName); file.SaveAs(savePath); <p>File uploaded successfully: @file.FileName</p>; } else { <p>No file selected.</p>; } }}
Summary
Task | Code / Concept |
---|---|
Create form | Use <form method="post"> or method="get" |
Access form data | Use Request.Form["fieldname"] |
Validate input | Check for empty or invalid values |
Retain form values | Set input value to @Request.Form["field"] |
File upload | Use enctype="multipart/form-data" and Request.Files |
If you want me to help with multi-step forms, CSRF protection, or advanced validation, just say!