ASP.NET Web Pages - HTML Form
- Previous Page WebPages Global
- Next Page WebPages Object
A form (a set of controls) is where you place input controls (text boxes, checkboxes, radio buttons, and dropdown menus) in an HTML document.
Create HTML Input Page
Razor instance
<html> <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 Instance
Razor instance - Displaying Image
Assuming you have three images in your image folder and you want to display these images dynamically based on the user's selection.
This can be easily achieved with a short snippet of Razor.
If the name of the image in the website's image folder is "Photo1.jpg", you can use the HTML <img> element to display this image, like this:
<img src="images/Photo1.jpg" alt="Sample" />
The following example demonstrates how to display an image selected by the user from a dropdown list:
Razor instance
@{ 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 Instance
Example Explanation
The server creates a variable named imagePath in the HTML page.
There is a variable named Choice ofDrop-down List(<select element>). It allows users to select a friendly (editor's note: easy to read) name (for example “)
Razor through Request["Choice"] Read the value of Choice. If the value exists, the code constructs a path to the image (images/Photo1.jpg) and stores the path in the variable imagePath .
The <img> element in the HTML page displays this image. When the page is displayed, the src attribute will be set to the value of the imagePath variable.
If the value of the variable imagePath is empty, it will prevent the <img> element from displaying a non-existent image (for example, when the page is first loaded).
- Previous Page WebPages Global
- Next Page WebPages Object