Web Pages Forms
ASP.NET Web Pages -HTML Form
A form is an HTML document in which input controls (text boxes, check boxes, radio selections) are placed buttons, drop-down lists).
Create an HTML input page
Razor instance
<!DOCTYPE html> <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><br> <input type="text" name="ContactName" value=""><br><br> <input type="submit" value="Submit" class="submit"> </form> } } </body> </html>
Run instance»
Click the "Run Instance" button to view the online instance
Razor Instance - Display Images
Suppose you have 3 images in your images folder that you want to Display images dynamically based on user selections.
This can be achieved with a simple piece of Razor code.
If you have an image named "Photo1.jpg" in your website's images folder, you can use the HTML <img> element to display the image, as shown below:
The following example demonstrates how to display users from the following list Image selected in:
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="Pic1.jpg">Photo 1</option> <option value="Pic2.jpg">Photo 2</option> <option value="Pic3.jpg">Photo 3</option> </select> <input type="submit" value="Submit"> @if(imagePath != "") { <p> <img src="@imagePath" alt="Sample"> </p> } </form> </body> </html>
Run Instance»
Click the "Run Instance" button to view the online instance
Explanation of examples
The server creates a variable called imagePath. The
HTML page has a drop-down list (<select> element) named Choice. It allows the user to choose a name of their own choosing (e.g. Photo 1), and when the page is submitted to the web server, a file name is passed (e.g. Photo1.jpg).
Razor code reads the value of Choice through Request["Choice"]. If the image path (images/Photo1.jpg) constructed through code is valid, assign the image path to the variable imagePath.
In HTML pages, the <img> element is used to display images. The src attribute is used to set the value of the imagePath variable when the page is displayed. The
<img> element is inside an if block. This is to prevent the image from being displayed without a name, such as when the page is first loaded.