2

I am new to MVC.I have saved the image and some data but can't display the saved images. I want to display all saved images in the main page.

Model: Get the db list from model

public List<Products> GenreList()
        {
}

Controller

public ActionResult MYsample()
{
    var MyList = storeDB.GenreList();
    var a= MyList.Count;

    if (a != null)
    {
        foreach (var li in MyList)
        {
            return File(li.fileContent, li.mimeType,li.fileName);
        }
    }
    return View(MyList);
}

View

    @foreach (var item in Model)
    {
            <img src="@Url.Action("MYsample", "HomeController", new { id = item.ProductID })" alt="@item.Productname" />
    }  
1
  • The problem is with the behavior of your code, return statement in for-loop will return first image as response and exit the function without hitting the view. BTW you could try what DarinDimitrov suggested +1 for that. Commented Feb 5, 2013 at 9:29

1 Answer 1

8

You could start by writing a controller action that will serve the images to the response stream:

public ActionResult Image(int id)
{
    // you should add a method to your repository that returns the image 
    // record from the id
    Products image = storeDB.Get(id);
    return File(image.fileContent, image.mimeType);
}

and then in your main controller action send the list of images to the view:

public ActionResult MySample()
{
    var model = storeDB.GenreList();
    return View(model);
}

and then in your strongly typed view loop through the images and generate an <img> tag for each image by pointing its src property to the newly created controller action:

@model MyList
@foreach (var li in MyList)
{
    <img src="@Url.Action("Image", new { id = li.Id })" alt="" />
}

If you don't want to have a separate controller action that will query the database and retrieve the image record from an id you could use the data URI scheme. Bear in mind though that this is not supported by all browsers.

So the idea is that your controller action will send the image data to the view:

public ActionResult MySample()
{
    var model = storeDB.GenreList();
    return View(model);
}

and then inside your strongly typed view you could loop through the list and generate the proper <img> tag:

@model MyList
@foreach (var li in MyList)
{
    <img src="src="data:@(li.mimeType);base64,@(Html.Raw(Convert.ToBase64String(li.fileContent)))" alt="" />
}
Sign up to request clarification or add additional context in comments.

1 Comment

why ToBase64String function is required to display image ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.