In order to display pictures stored in database, you have to do the following:
1) Create proper <img> tag in your view (html). There are several ways how to do it, for example
<img src='<%= imageUrl %>' />
or perhaps utilizing ASP.NET MVC v1.0 Futures method Html.BuildUrlFromExpression(...), or helpers Html.Image(...).
2) Once you have valid image tag in your view, you provide the actual image by loading the data from database and returning it from controller action. But first, you have to create a route definition to map image url and controller action method - I use
something like:
public static void RegisterRoutes(RouteCollection routes)
{
// ...
// Images have URL ~/Image/imageNameOrId, you can use the following in view:
// <img src='<%= Html.BuildUrlFromExpression<ImageController>(c => c.Image(item.PictureName)) %>" />
routes.MapRoute("Images", "{action}/{imageNameOrId}", new { controller = "Image" } );
// ...
}
public class ImageController : Controller
{
public ActionResult Image(string imageNameOrId)
{
// Input validation, error handling, caching etc. omitted for sake of clarity
byte[] imageBytes = LoadImageFromDatabase(imageNameOrId);
string contentType = GetImageContentType(); // e.g. "image/jpeg"
return File(imageBytes, contentType);
}
}
rickj1
hyperLink to an external site
A link to external site can be easily established via <a href="<%= item.UserHomePageUrl %>">User's home page</a>
Thanks CW2 I got hte link to work and I got the Image tage to show I wonder if you could give me a little more code to get the picture out of the data base and on the page in ASP.NET I use a genaric handler with a SQL select clause how do I put this all
togther in MVC hope you can help
I'm still learning where everything gose and how to put it all together in MVC
Hey, if his post helped your initial question, you should mark it as answered. Gives him points for helping you out.
So I'm not entirely sure I understand your question; you can actually still use generic handlers in MVC if you would like to, nothing precludes it. That said, to help you understand where things go, the way I would approach your app would be as follows:
-- Model of the user listings you mentioned, with URLs to the images already stored (in other words, I would probably *not* construct them on the fly). A separate model, if you like which defines the idea of an image resource (so, probably an ID of some
kind, a friendly description, and a byte[]).
-- Controller that routes to the user listings resource, and an ImageController which defines the usual CRUD (create read, update, delete) actions.
-- Views as appropriate. The Details action in this case might return a FileContentResult of the image data, so you wouldn't necessarily need a separate view file for that.
HOpe that helps.
Paul
Help those who have helped you... remember to "Mark as Answered"
I use a genaric handler with a SQL select clause how do I put this all togther in MVC
As Paul has mentioned in his message, you can still use generic handler in MVC application - just copy and include .ashx and .cs files in the project and change image source URL in the view so it matches the handler (e.g. <img src="ImageHandler.ashx?<%=
item.ImageNameOrId %>" />).
Also, you can use your existing SQL code to retrieve the image in MVC controller, just replace LoadImageFromDatabase(...) method I've used as a placeholder. This was ment as a quick test, you should consider moving such a method out of the controller to
some data layer (model, repository etc.).
here is the code I use in ASP.Net to render images and I reuse this in differnt apps and on difernt tables comments in the code point out where to change it to fit when I tyr to put it in mvc I can't seem to make it work
MVC seems to be a piece here and a piece there and put the pieces together to make it work that is where it is all falling apart for this problem I'm having user profiles and pictures in and out of a daata base is allmost a basic requirement for the web
today they should make it simple to do in the framework I tried that image tag example
the tag comes up on the page but no picture if you could be more clear would be a big help
/// <summary>
/// Returns Image from data base and writes it to data control
/// Using a GUID primary key
/// </summary>
// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(20));
//Copy and paste this image control in to the item template
//of a gridview or a listview to call this handler
// <asp:Image
//id="picAlbum" runat="server" Height ="250px" Width ="300px" AlternateText='<% #Eval("picture_tag") %>'
//ImageUrl='<%# "ShowImage.ashx?id=" + Eval("pic_id") %>' />
string picid;
if (context.Request.QueryString["id"] != null)
picid = (context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowAlbumImage(picid.ToString());
byte[] buffer = new byte[8192];
int byteSeq = strm.Read(buffer, 0, 8192);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 8192);
}
//context.Response.BinaryWrite(buffer);
}
/// <summary>
/// creates the connection and executes the select statment
/// against a GUID primary key
/// </summary>
/// <param name="picid"></param>
/// <returns></returns>
public Stream ShowAlbumImage(String picid)
{
//Change connection string "PictureAlbumConnectionString" to your own conection string
string conn = ConfigurationManager.ConnectionStrings["PictureAlbumConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
//Change Picture and UserProfiles to change tables
string sql = "SELECT Picture FROM PictureAlbum WHERE UserId= @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", new System.Guid(picid));
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
What does that mean, exactly? The handler is not invoked (e.g. breakpoint is not hit)? Compilation errors? You have to be more specific.
As I wrote before, you can use the generic handler in MVC application, the only thing needed is to generate correct URL for the image source. If you want to have a MVC controller, once you've defined a route for the images to let the controller handle image
src URLs, just implement action method like:
CW@ thanks for getting back to me I've tried every combination I can think of to get this to work If I dont get an error message I get an empty img tag if I try the image tab like this
alternatively, you could (and probably should) have the controller or viewmodel figure out the path, so that you can just have the view call somethign like Model.Url in that src field; that also makes your views less susceptible to change if you choose
to not use your handler anymore in the future.
Paul
Help those who have helped you... remember to "Mark as Answered"
rickj1
Member
385 Points
203 Posts
Enable Links and Display Pictures from data base in MVC app
Apr 17, 2009 07:24 PM|LINK
Im tring to display pictures and provide a link to that profiles home page
I have a data base the has a number of tables containing pictures and links to home pages for user profiles when users browes
they can click on a link and go to that web site in my mvc attemp I return a link but all it dose is a post back and the picture colum only shows
System.Byte[] There dosent seem to be a control for Images in MVC or a hyperLink to an external site
Can anyone help
Here is a link to the code I'm get by default http://forums.asp.net/t/1411112.aspx
MVC
www.barterlinks.net
CW2
Participant
938 Points
207 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 17, 2009 08:17 PM|LINK
In order to display pictures stored in database, you have to do the following:
1) Create proper <img> tag in your view (html). There are several ways how to do it, for example
<img src='<%= imageUrl %>' />
or perhaps utilizing ASP.NET MVC v1.0 Futures method Html.BuildUrlFromExpression(...), or helpers Html.Image(...).
2) Once you have valid image tag in your view, you provide the actual image by loading the data from database and returning it from controller action. But first, you have to create a route definition to map image url and controller action method - I use something like:
public static void RegisterRoutes(RouteCollection routes)
{
// ...
// Images have URL ~/Image/imageNameOrId, you can use the following in view:
// <img src='<%= Html.BuildUrlFromExpression<ImageController>(c => c.Image(item.PictureName)) %>" />
routes.MapRoute("Images", "{action}/{imageNameOrId}", new { controller = "Image" } );
// ...
}
public class ImageController : Controller
{
public ActionResult Image(string imageNameOrId)
{
// Input validation, error handling, caching etc. omitted for sake of clarity
byte[] imageBytes = LoadImageFromDatabase(imageNameOrId);
string contentType = GetImageContentType(); // e.g. "image/jpeg"
return File(imageBytes, contentType);
}
}
A link to external site can be easily established via <a href="<%= item.UserHomePageUrl %>">User's home page</a>
rickj1
Member
385 Points
203 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 19, 2009 01:42 AM|LINK
Thanks CW2 I got hte link to work and I got the Image tage to show I wonder if you could give me a little more code to get the picture out of the data base and on the page in ASP.NET I use a genaric handler with a SQL select clause how do I put this all togther in MVC hope you can help
I'm still learning where everything gose and how to put it all together in MVC
MVC
www.barterlinks.net
paul.vencill
Contributor
6716 Points
1358 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 19, 2009 02:20 AM|LINK
Hey, if his post helped your initial question, you should mark it as answered. Gives him points for helping you out.
So I'm not entirely sure I understand your question; you can actually still use generic handlers in MVC if you would like to, nothing precludes it. That said, to help you understand where things go, the way I would approach your app would be as follows:
-- Model of the user listings you mentioned, with URLs to the images already stored (in other words, I would probably *not* construct them on the fly). A separate model, if you like which defines the idea of an image resource (so, probably an ID of some kind, a friendly description, and a byte[]).
-- Controller that routes to the user listings resource, and an ImageController which defines the usual CRUD (create read, update, delete) actions.
-- Views as appropriate. The Details action in this case might return a FileContentResult of the image data, so you wouldn't necessarily need a separate view file for that.
HOpe that helps.
Paul
rickj1
Member
385 Points
203 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 19, 2009 04:15 AM|LINK
I'm looking for the code and procdure for displaying pictures from a data base with a GUID UserId
In MVC
MVC
www.barterlinks.net
CW2
Participant
938 Points
207 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 19, 2009 08:34 AM|LINK
As Paul has mentioned in his message, you can still use generic handler in MVC application - just copy and include .ashx and .cs files in the project and change image source URL in the view so it matches the handler (e.g. <img src="ImageHandler.ashx?<%= item.ImageNameOrId %>" />).
Also, you can use your existing SQL code to retrieve the image in MVC controller, just replace LoadImageFromDatabase(...) method I've used as a placeholder. This was ment as a quick test, you should consider moving such a method out of the controller to some data layer (model, repository etc.).
rickj1
Member
385 Points
203 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 19, 2009 07:47 PM|LINK
Thanks for gettting back to me
here is the code I use in ASP.Net to render images and I reuse this in differnt apps and on difernt tables comments in the code point out where to change it to fit when I tyr to put it in mvc I can't seem to make it work
MVC seems to be a piece here and a piece there and put the pieces together to make it work that is where it is all falling apart for this problem I'm having user profiles and pictures in and out of a daata base is allmost a basic requirement for the web today they should make it simple to do in the framework I tried that image tag example
the tag comes up on the page but no picture if you could be more clear would be a big help
/// <summary>
/// Returns Image from data base and writes it to data control
/// Using a GUID primary key
/// </summary>
// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(20));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetValidUntilExpires(true);
//Copy and paste this image control in to the item template
//of a gridview or a listview to call this handler
// <asp:Image
//id="picAlbum" runat="server" Height ="250px" Width ="300px" AlternateText='<% #Eval("picture_tag") %>'
//ImageUrl='<%# "ShowImage.ashx?id=" + Eval("pic_id") %>' />
string picid;
if (context.Request.QueryString["id"] != null)
picid = (context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowAlbumImage(picid.ToString());
byte[] buffer = new byte[8192];
int byteSeq = strm.Read(buffer, 0, 8192);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 8192);
}
//context.Response.BinaryWrite(buffer);
}
/// <summary>
/// creates the connection and executes the select statment
/// against a GUID primary key
/// </summary>
/// <param name="picid"></param>
/// <returns></returns>
public Stream ShowAlbumImage(String picid)
{
//Change connection string "PictureAlbumConnectionString" to your own conection string
string conn = ConfigurationManager.ConnectionStrings["PictureAlbumConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
//Change Picture and UserProfiles to change tables
string sql = "SELECT Picture FROM PictureAlbum WHERE UserId= @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", new System.Guid(picid));
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
www.barterlinks.net
CW2
Participant
938 Points
207 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 20, 2009 06:38 AM|LINK
As I wrote before, you can use the generic handler in MVC application, the only thing needed is to generate correct URL for the image source. If you want to have a MVC controller, once you've defined a route for the images to let the controller handle image src URLs, just implement action method like:
public ActionResult Image(string picid)
Yes, the MVC pattern is an excellent example of separating the concerns for better software maintainability. [8-|]{
// TODO: Validate input
return File(ShowAlbumImage(picid), "image/jpeg");
}
rickj1
Member
385 Points
203 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 21, 2009 02:27 AM|LINK
CW@ thanks for getting back to me I've tried every combination I can think of to get this to work If I dont get an error message I get an empty img tag if I try the image tab like this
<img src="ImageHandler.ashx?<%= item.Picture %>" />
If I let intelisence write the url to the imagehandler I get
<img src ="~/ImageHandler.ashx<%=(item.Picture) %>" alt ="" />
Tjis but one thing I think is wrong when I debug and step through the code I have the picture in the query
but when I get to the pic tag in Index the debuger steps over it and I have no intellisence in the pic tag
I'm about ready to give up and maybe look for an article or a demo if you have no more Ideas post it and I will mark this as answered
thanks rick
www.barterlinks.net
paul.vencill
Contributor
6716 Points
1358 Posts
Re: Enable Links and Display Pictures from data base in MVC app
Apr 21, 2009 04:35 AM|LINK
This looks like a routing and/or path issue. So, two things to try
First, add an routes.IgnoreRoute("{resource}.ashx?{id}"); to your global.asax
Second, your path is probably wrong, so if your ImageHandler.ashx file is at the root of your site, you want to type
<img src="<%= Url.Content("~/ImageHandler.ashx") + "?item.Picture" %>" alt="<%= item.Description %>" />alternatively, you could (and probably should) have the controller or viewmodel figure out the path, so that you can just have the view call somethign like Model.Url in that src field; that also makes your views less susceptible to change if you choose to not use your handler anymore in the future.
Paul