ASP.NET Web Pages - HTML Forms
Forms are the sections in an HTML document where input controls (text boxes, checkboxes, radio buttons, dropdown lists) are placed.
Creating an HTML Input Page
Razor Example
@{
if (IsPost) {
string companyname = Request["companyname"];
string contactname = Request["contactname"];
<p>You entered: <br /> @companyname <br /> @contactname </p>
}
else
{<form method="post" action="">}
}
Razor Example - Displaying an Image
Suppose you have 3 images in your image folder and you want to display an image dynamically based on user selection.
This can be achieved with a simple Razor code.
If you have an image named "Photo1.jpg" in your website's image folder, you can display the image using the HTML <img> element as follows:
The following example demonstrates how to display an image chosen by the user from a dropdown list:
Razor Example
@{
var imagePath="";
if (Request["Choice"] != null)
{imagePath="images/" + Request["Choice"];}
}
<!DOCTYPE html>
@if (imagePath != "")
{<p><img src="@imagePath" alt="Sample" /></p>}
Example Explanation
The server creates a variable named imagePath.
The HTML page has a dropdown list (a <select> element) named Choice. It allows the user to select a name (like Photo 1), and when the page is submitted to the web server, it passes a filename (like Photo1.jpg).
The Razor code reads the value of Choice through Request["Choice"]. If the image path (images/Photo1.jpg) built by the code is valid, it assigns the image path to the variable imagePath.
In the HTML page, the <img> element is used to display the image. When the page is displayed, the src attribute is used to set the value of the imagePath variable.
The <img> element is within an if block to prevent displaying an image without a name, such as when the page is first loaded.