Search code examples
c#asp.netentity-frameworkrazorengine

Showing Image on Index.cshtml page with Entityframework


I have this:

Controller:

[HttpPost]
        public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase file)
        {

            if (file != null && file.ContentLength > 0)
            {


                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                path = Url.Content(Path.Combine("~/~/App_Data/uploads", fileName));
                file.SaveAs(path);
            }



            if (ModelState.IsValid)
            {
                string username = User.Identity.Name;
                // Get the userprofile
                UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

                // Update fields
                user.Image = new byte[file.ContentLength];
                file.InputStream.Read(user.Image, 0, file.ContentLength);


                user.FirstName = userprofile.FirstName;
                user.LastName = userprofile.LastName;
                user.Email = userprofile.Email;
                user.Motto = userprofile.Motto;

                user.PlaceOfBirth = userprofile.PlaceOfBirth;
                user.HowManyBikes = userprofile.HowManyBikes;
                user.BesideYourBeth = userprofile.BesideYourBeth;
                user.NicestRide = userprofile.NicestRide;
                user.WorstRide = userprofile.WorstRide;
                user.AmountKmPerYear = userprofile.AmountKmPerYear;
                user.AverageSpeed = userprofile.AverageSpeed;
                user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding;
                user.PhoneNumber = userprofile.PhoneNumber;

                db.Entry(user).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("Edit", "Account");
            }

            return View(userprofile);
        }

And View:

@foreach (var item in Model)
            {
                                <tr>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.LastName)
                                    </td>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.FirstName)
                                    </td>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.Motto)
                                    </td>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.PlaceOfBirth)
                                    </td>

                                    <td><img width="200px" height="150px" src="@Url.Content(item.Image)" /></td>



                                    <td>

                                        @Html.ActionLink("Details", "Details", new { id = item.Id })

                                    </td>
                                </tr>
            }

                        </table>
                    </div>
                </div>
                <br />
                Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

                @Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

So I want to show the image in de index file, as thumbnail. The image is already saved in the database, and I try to show the image like this: <td><img width="200px" height="150px" src="@Url.Content(item.Image)" /></td> but that doesnt work.

Thank you for your help

and I have the Index, like this:

 @foreach (var item in Model)
                            {
                                <tr>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.LastName)
                                    </td>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.FirstName)
                                    </td>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.Motto)
                                    </td>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.PlaceOfBirth)
                                    </td>

                                    <td>
                                        <img width="200" height="150" src="@Url.Action("GetImage", "Account", new { item.Id })">
                                    </td>



                                    <td>

                                        @Html.ActionLink("Details", "Details", new { id = item.Id })

                                    </td>
                                </tr>
            }

but I look in chrome and I see the dimensions of: img 74x22 and also strange because the image is comming from:

img {
background-image: url('../Images/Large.JPG');
background-repeat: no-repeat;
background-position: top;
background-size: cover;
width: 100%;
height: 100%;

so for every profile the images are the same, but the images are stored in: ~/App_Data/uploads.

oke, I uncomment the img{} in site.css and now I see the right dimensions, but the images are broken

GET http://localhost:41787/Account/GetImage/34 500 (Internal Server Error) Account:179
event.returnValue is deprecated. Please use the standard event.preventDefault() instead. 

The accountController looks now this:

[HttpPost]
        public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase file)
        {

            if (file != null && file.ContentLength > 0)
            {


                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
               // path = Url.Content(Path.Combine("~/~/App_Data/uploads", fileName));
                file.SaveAs(path);
            }



            if (ModelState.IsValid)
            {
                string username = User.Identity.Name;
                // Get the userprofile
                UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

                // Update fields
                user.Image = new byte[file.ContentLength];
                file.InputStream.Read(user.Image, 0, file.ContentLength);
                user.ImageMimeType = file.ContentType;


                user.FirstName = userprofile.FirstName;
                user.LastName = userprofile.LastName;
                user.Email = userprofile.Email;
                user.Motto = userprofile.Motto;

                user.PlaceOfBirth = userprofile.PlaceOfBirth;
                user.HowManyBikes = userprofile.HowManyBikes;
                user.BesideYourBeth = userprofile.BesideYourBeth;
                user.NicestRide = userprofile.NicestRide;
                user.WorstRide = userprofile.WorstRide;
                user.AmountKmPerYear = userprofile.AmountKmPerYear;
                user.AverageSpeed = userprofile.AverageSpeed;
                user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding;
                user.PhoneNumber = userprofile.PhoneNumber;

                db.Entry(user).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("Edit", "Account");
            }

            return View(userprofile);
        }

        public FileContentResult GetImage(int itemId)
        {
            UserProfile user = db.userProfiles.FirstOrDefault(u => u.Id.Equals(itemId));
            if (user != null)
                return File(user.Image, user.ImageMimeType);
            else return null;
        }

and the view(Index.cshtml):

@foreach (var item in Model)
                        {
                            <tr>
                                <td>
                                    @Html.DisplayFor(modelItem => item.LastName)
                                </td>
                                <td>
                                    @Html.DisplayFor(modelItem => item.FirstName)
                                </td>
                                <td>
                                    @Html.DisplayFor(modelItem => item.Motto)
                                </td>
                                <td>
                                    @Html.DisplayFor(modelItem => item.PlaceOfBirth)
                                </td>

                                <td>
                                    <img width="200" height="150" src='@Url.Action("GetImage", "Account", new { item.Id  }, Request.Url.Scheme)'>
                                </td>



                                <td>

                                    @Html.ActionLink("Details", "Details", new { id = item.Id })

                                </td>
                            </tr>
        }

But is this correct??

<td>
                                        <img alt="" src="@Url.Action("GetImage", "Account", new {item.Id })" width="200" height="150"  class="Image" />
                                    </td>

Solution

  • instead of

    <img width="200px" height="150px" src="@Url.Content(item.Image)" />
    

    put

    <img width="200px" height="150px" src="@Url.Action("GetImage", "Account", new { item.Id })
    

    Add in your account controller this method :

    public FileContentResult GetImage(int itemId)
    {
    UserProfile user = db.userProfiles.FirstOrDefault(u => u.Id.Equals(itemId));
    if(user != null)
    return File(user.Image, user.ImageMimeType);
    else return null;
    }
    

    You must add a new field to the user table , ImageMimeType.

    In this section

    // Update fields
    user.Image = new byte[file.ContentLength];
    file.InputStream.Read(user.Image, 0, file.ContentLength);
    

    add

    user.ImageMimeType = file.ContentType;
    

    And that's it.

    Hope it helps.