Tuesday, July 5, 2011

ASP.NET Razor - Example



Add a little Razor code to display pictures by users choice

Sample Image  
I want to see:

Displaying an Image on a Web Page

If you have an image called "Photo1.jpg" in your images folder on your web site, you can display the image using an HTML <img> element like this:

<img src="images/Photo1.jpg" alt="Sample Photo" />


Displaying Images Dynamically

Suppose you have 3 images in your image folder, and you want to display images dynamically by the users choice.
This is easyly done by a little Razor code.
The example below shows how to display a selected which a user selects from a drop-down list:
@
{
var imagePath;
if( Request["Choice"] != null)
   {imagePath="images\" + Request["Choice"];}
}
<!DOCTYPE html>
<html>
<body>
<h1>Display Images</h1>
<form method="post" action="">
<div>
   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>
   &nbsp;
   <input type="submit" value="Submit" />
</div>
<div style="padding:10px;">
@if(imagePath != "")
{
<img src="@imagePath" alt="Sample" />}
</div>
</form>
</body>
</html>

Example explained

The server creates a variable called imagePath.
The HTML page has a drop-down list (a <select> element) named Choice. It lets the user select a friendly name (like Photo 1), and passes a file name (like Photo1.jpg) when the page is submitted to a web server.
The Razor code reads the value of Choice by Request["Choice"]. If it has a value the code constructs a path to the image (images/Photo1.jpg, and stores it in the variable imagePath.
In the HTML page there is an <img> element to display the image. The src attribute is set to the value of the imagePath variable when the page displays.
The <img> element is in an if block to prevent trying to display an image with no name (like the first time the page is displayed.

No comments:

Post a Comment