WebPages Examples
ASP.NET WebPages provides a wide range of functionalities for building dynamic and data-driven web applications. Below are some practical examples to illustrate how you can use WebPages features effectively in your projects.
Key Topics
Form Submission Example
Example
@{
if (IsPost)
{
var name = Request["name"];
Response.Write("Hello, " + name + "!");
}
}
<form method="post">
<label for="name">Enter your name:</label>
<input type="text" id="name" name="name" />
<button type="submit">Submit</button>
</form>
Explanation: This example demonstrates handling a simple form submission. The user's input is retrieved using the Request
object and displayed dynamically.
Database Interaction Example
Example
@{
var db = Database.Open("MyDatabase");
var users = db.Query("SELECT Name, Email FROM Users");
}
<h2>User List</h2>
<ul>
@foreach (var user in users)
{
<li>@user.Name (@user.Email)</li>
}
</ul>
Explanation: This example connects to a database, retrieves user data, and displays it in a simple HTML list using the WebPages Database
helper.
Dynamic Content Example
Example
@{
var currentTime = DateTime.Now;
var greeting = currentTime.Hour < 12 ? "Good Morning!" : "Good Afternoon!";
}
<h2>@greeting</h2>
<p>Current time is: @currentTime</p>
Explanation: This example uses Razor syntax to display a dynamic greeting based on the current time, showcasing how to incorporate logic directly into your WebPages application.
Key Takeaways
- WebPages makes it easy to handle form submissions and display user input dynamically.
- The Database helper provides seamless integration for data retrieval and display.
- Dynamic content generation allows for personalized and context-aware web applications.