Sonic
Sonic

Reputation: 111

How to Display Images Using MVC 4?

i'm new in mvc and I've mvc4 application i want to display pictures of Machines that ive been uploaded to server path

public partial class Picture
{
    public Picture()
    {
        this.Approvments = new HashSet<Approvment>();
    }

    public int PicId { get; set; }
    public string PicPath { get; set; }
    public Nullable<bool> Status { get; set; }
    public Nullable<System.DateTime> PickDate { get; set; }
    public Nullable<int> UserId { get; set; }
    public Nullable<int> ApproveId { get; set; }
    public Nullable<int> MacId { get; set; }

    public virtual ICollection<Approvment> Approvments { get; set; }
    public virtual Machine Machine { get; set; }
    public virtual User User { get; set; }
}

}

This is in my controller to upload to specific path

 public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                string name = Guid.NewGuid().ToString().Replace("-", "");
                var fileName = Path.GetFileName(file.FileName+name);
                var path = Path.Combine(Server.MapPath("~/App_Data/upload"), fileName);
                file.SaveAs(path);
            }
        }
        return RedirectToAction("Index");
    }

ive no idea where to go then to just display the images ??

Upvotes: 0

Views: 5949

Answers (2)

AthibaN
AthibaN

Reputation: 2087

In your Controller:

    public ActionResult DisplayPic()
    {
      Picture picture = new Picture();
      picture.PicPath = GetImagePath();  //Logic to get the image path as string
      return View(picture);
     }

In your View :

@model YourNameSpace.Model.Picture

<img src= "@Url.Content(Model.PicPath)" alt="Image"/>

Didn't check the code, but this should do..! Let me know if it helps

Upvotes: 1

mehmet mecek
mehmet mecek

Reputation: 2685

Create a folder on your www root directory to put your images like "MyImages" for example. If you save someImage.png into this directory, print the uri of this image www.yourdomainname/MyImages/someImage.png into your model and use it in your view.

Pass the image url list to the view like as follows

List<string> urlList = new List<string>();
urlList.Add("www.mydomainname.com/MyImages/image1.png");
urlList.Add("www.mydomainname.com/MyImages/image2.png");
urlList.Add("www.mydomainname.com/MyImages/image3.png");

return RedirectToAction("Index",urlList); //pass model into view

And on the view side use the model like this

@model List<string>
@foreach (string url in Model)
{
    <img src="@url"/>
}

Upvotes: 1

Related Questions