问题
Hi all I am having my _layout
as follows which works as per my requirement, but here there are couple of things I got strucked i.e I would like to display the corresponding image for that I write 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 is not showing image as per required for me so can some one help me I would like to display the image from the database after user logged in also I would like to display the session
values 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");
}
回答1:
You seem to have a problem with the <img>
syntax. It should be like this:
<img alt="" src="@Url.Action("GetPhoto","User", new { photoId = Session["UserName"].ToString() })" height="50" width="50" class="photo" />
According to the comments section you seem to have used the WebForms view engine in your actual code (<%= Html.Encode(Session["UserName"]) %>
).
This being said you have a far more serious issue with this code. The currently authenticated user should never be passed as parameter. That's a huge security vulnerability. So start by getting rid of it:
<img alt="" src="@Url.Action("GetPhoto", "User")" height="50" width="50" class="photo" />
and then inside your controller action you could retrieve 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");
}
来源:https://stackoverflow.com/questions/14686237/display-image-from-database-in-layout-in-mvc4