开发者

Display all images store in folder using ASP.net

I want to display all the images in my image's folder. This is my code :

 <% 
 string dir = Server.MapPath("Content/slideshow/images");
 string[] files;
 int numFiles;
 files = System.IO.Directory.GetFiles(dir);
 numFiles = files.Length;
             开发者_开发技巧    
 for (int i = 1; i < numFiles; i++)
 {
 %>
 <i><a href="#">
 <img src="/Content/slideshow/images/image<%= i %>.jpg" alt="" height="239px" width="930px" />
  </a></i>
 <% }%>

When I code like this, it display only the images that have the name "image"+blah blah blah . But I want to render all images in different name in a folder. Can anyone solve this?


I would suggest you using view models to achieve this. So let's start by defining such:

public class ImageViewModel
{
    public string Url { get; set; }
}

then we could have a controller action which will populate this view model (or precisely a collection of it):

public class ImagesController: Controller
{
    [ChildActionOnly]
    public ActionResult Images()
    {
        var appData = Server.MapPath("~/Content/slideshow/images");
        var images = Directory.GetFiles(appData).Select(x => new ImageViewModel
        {
            Url = Url.Content("~/Content/slideshow/images/" + Path.GetFileName(x))
        });
        return PartialView(images);
    }
}

then we could define a corresponding partial view (~/Views/Shared/Images.ascx):

<%@ Control 
    Language="C#"    
    Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<ImageViewModel>>" 
%>
<%= Html.DisplayForModel() %>

next a corresponding display template which will be rendered for each image (~/Views/Shared/DisplayTemplates/ImageViewModel.ascx):

<%@ Control 
    Language="C#"    
    Inherits="System.Web.Mvc.ViewUserControl<ImageViewModel>" 
%>
<img src="<%= Model.Url %>" alt="" height="239px" width="930px" />

and the final part that's left is to include this child action somewhere in a view or a master page:

<%= Html.Action("Images", "Images") %>


public DisplayImages() {

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Location);
foreach (System.IO.FileInfo f in dir.GetFiles("*.*")) 
{
    //Do Something
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜