Display Images in Asp.net MVC


Here i am describe how to display images in Asp.net MVC.

-> First of all create the Asp.net MVC project and you can get Model, View, Content, Controllers and Scripts folder.

-> Now you can add One another folder says "Images" and in that you can add your image which you want to display.

-> After adding images you can add one xml file in your Images floder say "DisplayImage.xml".

-> In xml you can writer this way


<?xml version="1.0" encoding="utf-8" ?>
<images>
<image>
<ImageFile>1.gif</ImageFile>
<Description>XYZ</Description>
</image>
<image>
<ImageFile>2.gif</ImageFile>
<Description>ABC</Description>
</image>
</images>


-> After that you can add one css class in Model Folder say Images.cs file and add following code in that

using System.Xml.Linq;
using System.Web;
public class Images
{
public Images()
{

}
public string Path { get; set; }
public string Description { get; set; }

public List GetAllImage()
{
string directoryOfImage = HttpContext.Current.Server.MapPath("~/Images/");
XDocument imageData = XDocument.Load(directoryOfImage + @"ImageMetaData.xml");
var images = from image in imageData.Descendants("image")
select new Images{ Path = image.Element("filename").Value, Description = image.Element("description").Value };

return images.ToList();
}
}


-> After that you can add one Controller in Controller folder say "ImageController".So in create one index method in that method you can access
the Images model's GetAllImage() method this way

public ActionResult Index()
{
Image ObjGetImage = new Image();
List ObjImage = ObjGetImage.GetAllImage();
return View(ObjImage);
}


-> Now right click on the index method and click on "Add View". Which create the one image folder in the view folder in that it create one Index.aspx file.In that you can do this way

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<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>


-> After all the things is completed then you can add one li tag

<li><%=Html.ActionLink("Images","Index","Image") %></li>


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: