5

I am saving image files in a folder /images/profile and i want to save the image path in a database and do not know how to display image in a view. I am new to MVC. Following are the codes for image uploading. Please help.

HomeController.cs

public class HomeController : Controller
    {

        ImageEntities db = new ImageEntities();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult FileUpload(HttpPostedFileBase file, tbl_Image model)
        {
            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                string path = System.IO.Path.Combine(
                                       Server.MapPath("~/images/profile"), pic);
                // file is uploaded
                file.SaveAs(path);

            }

    return View("FileUploaded", db.tbl_Image.ToList());

        }

        public ActionResult FileUploaded()
        {
            return View();
        }

    }

FileUpload.cshtml

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

FileUploadedView.cshtml

@foreach (var item in Model)
    { 
   <img src="~/images/profile/@item.imagepath" />
    }

3 Answers 3

1

You shoud save image name instead of image path in table.

Then in view try this:

<img src="~/images/profile/@Model.imageUrl" />

"Update"

See here:

How to save image in database and display it into Views in MVC?

Sign up to request clarification or add additional context in comments.

1 Comment

Now only image border is displaying not the image i have updated my code. Thanks for your suggestion
0

save the image path like this: "~/images/profile/mypic.jpg"

and then in you view:

 <img src="@Url.Content("~/images/profile/mypic.jpg")" />

or in case you have a Photo class: (consider "item" as your image)

 <img src="@Url.Content(item.Path)" />

thats it.

Comments

0

According to the suggestion of Samiey Mehdi I did this at my code for making it work

In the Controller:

newRecord.flName = ImageName;

In the View:

<img src="~/images/@item.flName" width="100" height="100" />

Comments

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.