.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> Architecture/Pattern >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Image Gallery in ASP.Net MVC Framework

Posted By:Dhananjay Kumar       Posted Date: December 13, 2009    Points: 25    Category: Architecture/Pattern    URL: http://www.dotnetspark.com  
 

Image Gallery in ASP.Net MVC Framework


Objective

Objective of this aricle is to show, how to work with Images in ASP.Net MVC application. This article will explain, how to display images from Xml file and how to add images in Xml resourece.

The Final Output would be something like below.

image1.gif

Creating the Resource folder for Image

  • Create a ASP.Net MVC application, by New->Project->Web->ASP.Net MVC Application.
  • Now add a folder in application and give it name as Images.

    image2.gif
     
  • Add few images in Images folder. For that right click on Image folder and add existing items.

    image3.gif

     image4.gif
  • After adding Images in Images folder. Folder will look like below. 

    image5.gif
     
  • Add an XML file in Image directory as source of the images. Give any name, here name is ImageMetaData.xml. To add XML file in Images directory, right click on directory and add XML File as shown below.

    image6.gif
     
  • Create XML elements for images. Here filename and description are xml elements. Give value according to name of your added images. For my Images the xml file is as below.

    xml version="1.0" encoding="utf-8" ?>
    <images>
      <
    image>
      <
    filename>anthonyrobins.jpgfilename>
      <description>Anthony Robbinsdescription>
      image>
      <
    image>
      <
    filename>chetanbhagat.jpgfilename>
      <description>Chetan Bhagatdescription>
      image>
      <
    image>
      <
    filename>deepak.jpgfilename>
      <description>Deepak Chopradescription>
      image>
      <
    image>
      <
    filename>robinsharma.jpgfilename>
      <description>Robin Sharamadescription>
      image>
      <
    image>
      <
    filename>stevenkovey.jpgfilename>
      <description>Steven Coveydescription>
      image>
      <
    image>
      <
    filename>taslima.jpgfilename>
      <description>Taslima Nasrrendescription>
      image>
      <
    image>
      <
    filename>vikarm.jpgfilename>
      <description>Vikram Sethdescription>
      image>
    images>

    Displaying Images

    Creating the Model

    Right click on Model folder and add new class. Give name of the class as Image.

    image7.gif

    image8.gif

    Type the below code inside the Image class. This class is acting as a business class. This class got two properties . One for Path of the image and other for Description of the image.

    Image.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web; namespace ImageViewer.Models
    {
      public class Image
      {   public Image(string path, string desc)
      {
      Path = path;
      Description = desc;   }
      public string Path { get; set; }
      public string Description { get; set;}
      }
    }


    We need to fetch data from the disk. For this, we will add one more model class and in constructor of that class, we will fetch all the images from xml file. So add one class in Model folder as shown in step above. Give name ImageModel.

    ImageModel.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Xml.Linq;

    namespace ImageViewer.Models
    {
      public class ImageModel:List<Image>
      {
      public ImageModel()
      {
      string directoryOfImage = HttpContext.Current.Server.MapPath("~/Images/");
      XDocument imageData = XDocument.Load(directoryOfImage + @"/ImageMetaData.xml");
      var images = from image in imageData.Descendants("image") select new Image(image.Element("filename").Value, image.Element("description").Value);
      this.AddRange(images.ToList<Image>()); 
      }
      }
    }


    Creating the Controller

    Right Click on Controller and add a controller called ImageController.

    image9.gif

    Type or paste below code inside ImageController class. This class got an action, which is returning View with instance of ImageModel in View dictionary.

    Controller\ImageController.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Xml.Linq; namespace ImageViewer.Models
    {
      public class ImageModel:List<Image>
      {
      public ImageModel()
      {
      string directoryOfImage = HttpContext.Current.Server.MapPath("~/Images/");
      XDocument imageData = XDocument.Load(directoryOfImage + @"/ImageMetaData.xml");
      var images = from image in imageData.Descendants("image") select new Image(image.Element("filename").Value, image.Element("description").Value);
      this.AddRange(images.ToList<Image>()); 
      }
      }
    }

    Creating the View

    Right click on View folder and add new View. Name of the View must be Index because controller name is here Index.

    image10.gif

     image11.gif

    1. using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.Mvc;
      using ImageViewer.Models;
      namespace ImageViewer.Views.Image|
      {
        public partial class Index : ViewPage<ImageModel>
        {
        }
      }

    2. <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ImageViewer.Views.Image.Index" CodeBehind="~/Views/Image/Index.cs" %>
      <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
        Index
      asp:Content>
      <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <% foreach (var image in ViewData.Model) { %>
        <span class="image">
        <a href="images/<%= image.Path %>">
        <img src="images/<%= image.Path %>" height="100" width="100" />a>
        <span class="description"><%= image.Description %>span>
        span>
      <% }%>
       
      asp:Content>
      Adding Link to navigate Image from Home page
      1. <li><%=Html.ActionLink("Images","Index","Image") %>li>

        So, now three action links would be there in master page

          <ul id="menu"> 
          <li><%= Html.ActionLink("Home", "Index", "Home")%>li>
          <li><%= Html.ActionLink("About", "About", "Home")%>li>
          <li><%=Html.ActionLink("Images","Index","Image") %>li>
         ul>

        Press F5 to run with debugging

        image12.gif

        Click on Image tab to get Images.

        image13.gif
      public void Add(Image image, HttpPostedFileBase filebase)
        {
        string imagerep = HttpContext.Current.Server.MapPath("~/Images/");
        filebase.SaveAs(imagerep + image.Path);
        this.Add(image);
        XElement xml = new XElement("images", from i in this
        orderby image.Path
        select new XElement("image",
        new XElement("filename", i.Path),
        new XElement("description", i.Description))
        );
        XDocument doc = new XDocument(xml);
        doc.Save(imagerep + "/ImageMetaData.xml");
       
        }

      So, now the ImageModel class is been modified to

      Models\ImageModel.cs

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Xml.Linq; namespace ImageViewer.Models
      {
        public class ImageModel:List<Image>
        {
        public ImageModel()
        {
        string directoryOfImage = HttpContext.Current.Server.MapPath("~/Images/");
        XDocument imageData = XDocument.Load(directoryOfImage + @"/ImageMetaData.xml");
        var images = from image in imageData.Descendants("image") select new Image(image.Element("filename").Value, image.Element("description").Value);
        this.AddRange(images.ToList<Image>()); 
        }   public void Add(Image image, HttpPostedFileBase filebase)
        {
        string imagerep = HttpContext.Current.Server.MapPath("~/Images/");
        filebase.SaveAs(imagerep + image.Path);
        this.Add(image);
        XElement xml = new XElement("images", from i in this
        orderby image.Path
        select new XElement("image",
        new XElement("filename", i.Path),
        new XElement("description", i.Description))
        );
        XDocument doc = new XDocument(xml);
        doc.Save(imagerep + "/ImageMetaData.xml");   }
        }
      }

      Amending the Controller

      In ImageController add actions which will perform task of adding the image into the resource. For that add below actions called Add and Save in Image Controller.

      image14.gif

      So, now Image Controller would look like below. Both Add and Save actions are highlighted in different colors.

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.Mvc;
      using System.Web.Mvc.Ajax;
      using ImageViewer.Models; namespace ImageViewer.Controllers
      {
        public class ImageController : Controller
        {
        //
        // GET: /Image/   public ActionResult Index()
        {
        return View(new ImageModel());   }

        public ActionResult Add()
        {
        return View();
        }
          [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save()
        {
        foreach (string name in Request.Files)
        {
        var file = Request.Files[name];
       
        string fileName = System.IO.Path.GetFileName(file.FileName);
        Image image = new Image(fileName, Request["description"]);
       
        ImageModel model = new ImageModel();
        model.Add(image, file);
        }
        return RedirectToAction("index");
        }
        }

      }

      Creating the View

      Right click on View folder and add new View. Name of the View must be Index because controller name is here Add.

      image15.gif

       image16.gif
      1. using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Mvc;
        using ImageViewer.Models;
        namespace ImageViewer.Views.Image
        {
          public partial class Add: ViewPage<ImageModel>
          {
          }
        }
         
      2. <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" CodeBehind="~/Views/Image/Add.cs" %>
         
        <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
          Add
          <form method="post" action="<%=Url.Action("Save") %>" enctype="multipart/form-data">
          <input type="file" name="file" />
          <input type="submit" value="submit" /> <br />
          <input type="text" name="description" />
        form>
        asp:Content>

        Amending Views\Index.aspx

        Add below ActionLink in index.aspx.

        <p><%= Html.ActionLink("Add your own image", "Add", "Image")%>p>

        So, Now modified Index.aspx will look like below,

        <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ImageViewer.Views.Image.Index"
        CodeBehind="~/Views/Image/Index.cs" %>
        <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
          Index

        asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
          <% foreach (var image in ViewData.Model) { %>
          <span class="image">
          <a href="images/<%= image.Path %>">
          <img src="images/<%= image.Path %>" height="100" width="100" />a>
          <span class="description"><%= image.Description %>span>   span>
        <% }%>   <p><%= Html.ActionLink("Add your own image", "Add", "Image")%>p> asp:Content>

        Press F5 to run the application

        image17.gif

        Click on Add your own image to add new Image. Browse the Image, give a description and click on submit button.

        image18.gif

        image19.gif


      Future Scope:
      1. To add functionality for Delete and update Description for a particular image.
      2. Modify the data source from an xml file to database.
      How to use Zip file:

      Just download Zip file and run it.

      Happy Coding.

  •  Subscribe to Articles

         

    Further Readings:

    Responses
    Author: Mircea         Company URL: http://www.dotnetspark.com
    Posted Date: April 24, 2010

    I have Microsoft Visual Web Dev 2008 and could not open your project example.
    So i buit my project and trying to run this example i got the error:
    ===foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator' ===

    inside the index view file on the line:
    <% foreach (var image in ViewData.Model) { %>

    the ImageController:
    public class ImageController : Controller
    {
    public ActionResult Index()
    {
    return View(new ImageModel());
    }
    ..............}
    the ImageModel.cs
    public class ImageModel : List<Image>
    {
    public ImageModel()
    {
    ......}

    the image class
    public class Image
    {
    public string Path { get; set; }
    .....}

    May i know why?
    Author: Mircea         Company URL: http://www.dotnetspark.com
    Posted Date: April 26, 2010

    I solved my problem.
    In your project the expression - CodeBehind="~/Views/Image/Index.cs" - is included manually in Index.aspx like:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ShowImages.Views.Image.Index" CodeBehind="~/Views/Image/Index.cs" %>

    Good trick for an IEnumerable including missing

    Post Comment

    You must Sign In To post reply
    Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

    Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend