Display image from database in _layout in mvc4

Hi everyone, I have mine _layout

as follows, which works as per my requirement, but there are a few things here that I am amazed at. I would like to display the corresponding image which I am writing as follows

@if (Session["UserName"] != null)
{
 <div class="logged_in" id="user_navigation" runat="server">
 <a title="Your Profile" href="">
 <img alt="" src="@Url.Action("GetPhoto", new { photoId = Session["UserName"] })" height="50" width="50" class="photo" />
</a>
</div>
}

      

But this doesnt show the image as required for me, so can someone help me. I would like to display an image from the database after the user is logged in. Also I would like to display values session

in some control too

This is my controller code

public ActionResult GetPhoto(string photoId)
        {
            byte[] photo = null;
            var v = db.tblUsers.Where(p => p.UserName == photoId).Select(img => img.Photo).FirstOrDefault();
            photo = v;
            return File(photo, "image/jpeg");
        }

      

+3


source to share


1 answer


You have a syntax problem <img>

. It should be like this:

<img alt="" src="@Url.Action("GetPhoto","User", new { photoId = Session["UserName"].ToString() })" height="50" width="50" class="photo" />

      

As per the comments section, you seem to have used the WebForms view engine in your actual code ( <%= Html.Encode(Session["UserName"]) %>

).

Speaking of which, you have a much bigger problem with this code. An authenticated user should never be passed as a parameter. This is a huge security vulnerability. So start with this:



<img alt="" src="@Url.Action("GetPhoto", "User")" height="50" width="50" class="photo" />

      

and then inside your controller action you can get it:

public ActionResult GetPhoto()
{
    string user = Session["UserName"] as string;
    byte[] photo = db
        .tblUsers
        .Where(p => p.UserName == user)
        .Select(img => img.Photo)
        .FirstOrDefault();
    return File(photo, "image/jpeg");
}

      

+6


source







All Articles