ASP.NET Web Pages - HTML Forms
A form is the part of an HTML document where input controls (text boxes, checkboxes, radio buttons, drop-down lists) are placed.
Create an HTML Input Page
Razor Example
<body>
@{
if (IsPost) {
string companyname = Request["companyname"];
string contactname = Request["contactname"];
<p>You entered: <br />
Company Name: @companyname <br />
Contact Name: @contactname </p>
}
else
{
<form method="post" action="">
Company Name:<br />
<input type="text" name="CompanyName" value="" /><br />
Contact Name:<br />
<input type="text" name="ContactName" value="" /><br /><br />
<input type="submit" value="Submit" class="submit" />
</form>
}
}
</body>
</html>
Run Example »
Razor Example - Displaying Images
Suppose there are 3 images in your image folder, and you want to display an image dynamically based on the user's choice.
This can be achieved with a simple piece of Razor code.
If there is an image named "Photo1.jpg" in your website's image folder, you can use the HTML <img> element to display the image, as follows:
The following example demonstrates how to display the image selected by the user from the drop-down list:
Razor Example
var imagePath="";
if (Request["Choice"] != null)
{imagePath="images/" + Request["Choice"];}
}
<!DOCTYPE html>
<html>
<body>
<h1>Display Images</h1>
<form method="post" action="">
I want to see:
<select name="Choice">
<option value="Photo1.jpg">Photo 1</option>
<option value="Photo2.jpg">Photo 2</option>
<option value="Photo3.jpg">Photo 3</option>
</select>
<input type="submit" value="Submit" />
@if (imagePath != "")
{
<p>
<img src="@imagePath" alt="Sample" />
</p>
}
</form>
</body>
</html>
Run Example »
Example Explained
The server creates one calledimagePathvariable.
The HTML page has one namedChoiceofdrop-down list(<select> element). It allows the user to select a name as they wish (such asPhoto 1), when the page is submitted to the Web server, a file name is passed (such asPhoto1.jpg)。
Razor code, throughRequest["Choice"]reads the value of Choice. If the image path constructed by the code (images/Photo1.jpg) is valid, assign the image path to the variableimagePath。
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 in an if block, to prevent displaying an image without a name, such as when the page is first loaded.
Other Extensions