c# - ASP.NET -Retrieving a list of images from the Database and display them in the view? -
i retrieve list of images database , display them on view. images stored in 'image' data type format in database. below controller, view model, , view. i'm not sure if correct, please help. i've used linq2sql since it's sample project. please correct code, , me how display list of images on view. i'm beginner, it'd great if please keep solution straight , simple.
viewmodel:
public class imageviewmodel { public byte[] image { get; set; } public int imageid { get; set; } public ienumerable<int> imagelist { get; set; } }
controller: *(updated , solved)*
public actionresult index() { var imageslist = (from q in ctx.images select new models.imageviewmodel { imageid = q.id }).tolist(); ienumerable<int> imageids = imageslist.select(x=>x.imageid); models.test obj = new models.test(); obj.imagelist = imageids; return view(obj); } public actionresult view(int imageid) { byte[] imagearray = (from q in ctx.images q.id == imageid select q.data.toarray()).firstordefault(); return file (imagearray,"image/jpg"); }
view:
@model mvcapplication3.models.imageviewmodel @foreach (var id in model.imagelist) { <img src="@url.action("view", "home", new { imageid = id},null)" /> }
britton recommended i'll reiterate.
you should have 2 actions/views achieve want. 1 retrieve single image, , list of images using action mentioned before retrieve single image.
here's rough example of mean. haven;t tested ensure compiles should give rough idea of how this.
class imagelibrary } public actionresult list() { //i'm going assume here have sort of service or repository obtaining images @ point. //this doesn't retrieve actual image data, metadata. it's less of hit on db way var imageslist = imageservice.listallimages() ienumerable<int> imageids = imageslist.select(x=>x.imageid) return view("list", imageids) } public actionresult view(int imageid) { var image = imageservice.getimage(imageid); var contentdisposition = new system.net.mime.contentdisposition() { filename = image.name, inline = true }; response.appendheader("content-disposition", contentdisposition.tostring()); return file(image.data, image.contenttype); //including content type since i'm assuming image jpg, gif, png, etc./ } }
and in imagelibrary/list
view.
@foreach(var id in model) { <img src="@url.action("view", "imagelibrary", new {imageid = id})"> }
Comments
Post a Comment