I want to some images in asp repeater which comes from databas image table.
HTML
<asp:Repeater ID="rpt_" runat="server">
<ItemTemplate>
<li>
<img src="<%="data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("Photo")) %>" alt="" />
</li>
</ItemTemplate>
</asp:Repeater>
C#
private void Load_()
{
ClassDo class_ = new ClassDo;
DataTable dt = class_.Ann().Tables[0];
rpt_.DataSource = dt;
rpt_.DataBind();
}
These are my codes, and get me error I cannot show images.
HTML
<img alt="" src="<%="data:image/jpg;base64," + Convert.ToBase64String(Class_._image) %>" />
C#
Class_._image = (byte[])dt.Rows[0]["Photo"];
It works like that somewhere else, but with repeater I cannot read it with Eval.
Is there any working way to show images?
Can you try this?
Create a function
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
}
Then change your declaration like this
<asp:Image ImageUrl='<%# GetImage(Eval("Photo")) %>' />
Related
I want to transfer the text of a hyperlink through a session inside a repeater. But I can not think of the logic to do this. My repeater generates links within that dropdown menu and I want to get the text that appears in the link and pass it to another page Sectors.aspx. This is what I have done so far:
--- edit ---
I want that when the link is clicked, the text that is in the link is passed to the other page. For example, the menu has two links, APPLE and BANANA. When the user clicks APPLE, I want the next page Sectors.aspx to know that the user clicked APPLE and not the other options.
ASPX Page:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="dropdown">
<button class="dropbtn">Setor</button>
<div class="dropdown_content">
<asp:Repeater ID="sectors_menu" runat="server">
<ItemTemplate>
<asp:HyperLink id="hyperlink1" NavigateUrl="Sectors.aspx" Text='<%#((System.Data.DataRowView)Container.DataItem)["sector"] %>' runat="server"></asp:HyperLink>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</asp:Content>
Code Behind
public partial class _Default : System.Web.UI.Page
{
MySqlConnection mysql_connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
string mysql_string;
MySqlDataAdapter mysql_data_adapter;
public void Page_Load(object sender, EventArgs e)
{
Sector_label();
}
public void Sector_label()
{
mysql_string = "SELECT * FROM employees GROUP BY sector";
mysql_data_adapter = new MySqlDataAdapter(mysql_string, mysql_connection);
DataTable data_table = new DataTable();
mysql_data_adapter.Fill(data_table);
DataView data_view = new DataView(data_table);
sectors_menu.DataSource = data_view;
sectors_menu.DataBind();
for (int count = 0; count < sectors_menu.Items.Count; count++)
{
var test = (HyperLink)sectors_menu.Items[count].FindControl("hyperlink1");
Session["session_hyperlink"] = test.Text;
// Debug.WriteLine(test.Text);
}
}
}
You could add the text as a parameter of the NavigateUrl:
<ItemTemplate>
<asp:HyperLink id="hyperlink1" NavigateUrl='<%# "Sectors.aspx?sector=" + Server.UrlEncode(((System.Data.DataRowView)Container.DataItem)["sector"]).ToString() %>' Text='<%#((System.Data.DataRowView)Container.DataItem)["sector"] %>' runat="server"></asp:HyperLink>
</ItemTemplate>
Then, Sectors.aspx can retrieve it through the "sector" parameter:
protected void Page_Load(object sender, EventArgs e)
{
string sector = Request.Params["sector"];
}
That id="hyperlink1" parameter looks fishy, though. You don't want all your hyperlinks to have the same ID.
Just replace hyperlink tag with this code ,
<asp:HyperLink runat="server" Navigateurl='<%#"Sectors.aspx?mySector="+ Eval("sector") %>'
Text='<%#((System.Data.DataRowView)Container.DataItem)["sector"] %>' />
Please, my senior code experts, I have a repeater that randomly display the images and text label from a folder using a jquery. I want to be able to select and click the current image such that it redirects to another page where the image details can be displayed. I will appreciate your help and contributions!
<div id="banner-fade">
<!-- start Basic Jquery Slider -->
<ul class="bjqs">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<li>
<img src='<%# DataBinder.Eval(Container.DataItem,"Value") %>' title='<%# (DataBinder.Eval(Container.DataItem,"Text").ToString()).Split('.')[0].ToString() %>' alt=""></li>
</ItemTemplate>
</asp:Repeater>
</ul>
<!-- end Basic jQuery Slider -->
</div>
Below is the code behind...
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/pages/Management/Images/Products/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "/pages/Management/Images/Products/" + fileName));
}
Repeater1.DataSource = files;
Repeater1.DataBind();
}
Surround the <img> with a link.
<a href="www.linkToPageHere.com">
<img src='<%# DataBinder.Eval(Container.DataItem,"Value") %>' title='<%# (DataBinder.Eval(Container.DataItem,"Text").ToString()).Split('.')[0].ToString() %>' alt="">
</a>
I'm not sure if this is the right approach, but still went ahead.
The template has these fields
Description [Rich Text]
Images [TreelistEx]
User will select pics from the media library using the TreelistEx field, which later would be displayed in a carousel. User should also be able to edit those images.
My code is not displaying any images.
aspx:
<div class="toggle_1bs">
<asp:Repeater ID="rpImages" runat="server" OnItemDataBound="rpImages_ItemDataBound"
ItemType="Sitecore.Data.Items.Item">
<HeaderTemplate>
<div id="1bs" class="owl-carousel">
</HeaderTemplate>
<ItemTemplate>
<div class="item">
<sc:Image ID="imgMain" Field="Images" runat="server" CssClass="img-full"
Item="<%#Container.DataItem %>"/>
</div>
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
</asp:Repeater>
</div>
aspx.cs:
private void BindData()
{
//bind data to the repeater
MultilistField offerImages = (MultilistField)offerDetails.Fields["Images"];
rpImages.DataSource = offerImages.GetItems();
rpImages.DataBind();
}
protected void rpImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var mainItem = (Item)e.Item.DataItem;
if (mainItem != null)
{
var imgMain = (Image)e.Item.FindControl("imgMain");
if(imgMain != null)
{
if (!string.IsNullOrEmpty(MediaManager.GetMediaUrl(mainItem)))
imgMain.DataSource = MediaManager.GetMediaUrl(mainItem);
//Response.Write(MediaManager.GetMediaUrl(mainItem));
}
}
}
There are 2 images added using the treelist control and I can see the html rendered for the 2 images (<div class="item"></div>).
You don't have field which is an Image type field. That's why you cannot use sc:Image like that.
You're getting list of media items from your TreeListEx.
Remove your rpImages_ItemDataBound and try something like this instead:
<ItemTemplate>
<img src='<%# Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl((Sitecore.Data.Items.Item)Container.DataItem)) %>' />
</ItemTemplate>
I am trying to integrate a JavaScript photo album in ASP.NET (C#).
The code which I have uses hardcoded images; I want to fetch those images dynamically.
<div class="image_stack" style="margin-left:300px">
<img id="photo1" class="stackphotos" src="photos/4.jpg" >
<img id="photo2" class="stackphotos" src="photos/5.jpg" >
<img id="photo3" class="stackphotos" src="photos/6.jpg" >
</div>
I want to replace these hardcoded photos with 3 URLs fetched from a database. How can I achieve this?
One simple way:
use ASP:Image control
<asp:Image ID="photo1" class="stackphotos" runat="server" ImageUrl=" " />
<asp:Image ID="photo2" class="stackphotos" runat="server" ImageUrl=" " />
<asp:Image ID="photo3" class="stackphotos" runat="server" ImageUrl=" " />
then you can assign ImageUrl on the server Side i.e.
var obj= GetUserImages(); //method fetching image urls from db.
photo1.ImageUrl = obj.ImageUrl1;
photo2.ImageUrl = obj.ImageUrl2;
photo3.ImageUrl = obj.ImageUrl3;
2. you can simply place runat="server" attribute on your existing img tags and access them on the server side and set their url. i.e place runat="server" on your img like below
<img id="photo1" runat="server" class="stackphotos" src="photos/4.jpg" >
and then access this on server side like
photo1.Src = dbObject.Url;
3. you can dynamically insert imgs from the server side in a loop.
string imgs = string.Empty;
foreach(var item in GetAllUserImages())
{
images +="<img src='"+ item.ImageUrl +"' class='stackphotos' />";
}
div1.InnerHtml= images;
where div is
<div id="div1" runat="server">
</div>
4. you can call a webmethod (a method on your .aspx.cs page, marked with attribute [WebMethod] and call it via ajax and update your img tags in a javascript function.
Page:
<%# Page Language="C#" %>
other page content
<asp:PlaceHolder runat="server" ID="myimages" />
other page content
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
using(var db = new myDataContext()) // see linq to sql / entity framework
foreach(var i in db.ImagesTable.Select(img => new { Id = img.Id })) // ImagesTable is the name of your table with info about your images
myimages.Controls.Add(new LiteralControl(#"<img src=""myimgdir/" + i.Id + "".jpg" class=""stackphotos"" />")); // presuming that images are named according to an id in the database
}
I am trying to provide alternate image as some of the images are corrupt and do not get display, I tried with js but no success, so need help and suggestions on how to do the same. the scenario is on page load the information of students get bound to DataList and on the basis of it image is pulled from another table by GetImage class but the problem is some images are corrupt so I want to display another dummy image. I changed BG image using CSS but its not as expected.
<asp:DataList ID="DataList1" CssClass="slider" r RepeatColumns="6" RepeatDirection="Vertical" runat="server" OnEditCommand="DataList1_EditCommand" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<ul>
<li><a class="info" href="#">
<asp:ImageButton CssClass="imagetest" AlternateText=" " ID="Image1" name="mybutton" runat="server" Width="140" Height="140" CommandName="image" OnLoad="changeImage();" CommandArgument="image" CausesValidation="false" ImageUrl='<%# "GetImage.aspx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>'
</li>
</ul>
</ItemTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
string city = Request.QueryString["city"];
string RollNo = Request.QueryString["RollNo"];
string state = Request.QueryString["state"];
string fname = Request.QueryString["fname"];
string lname = Request.QueryString["lname"];
DataAccess dao = new DataAccess();
dao.openConnection();
byte[] arr = dao.GetPicture(city, RollNo, state, fname, lname);
//Response.BinaryWrite(arr);
try
{
Response.BinaryWrite(arr);
}
catch (Exception) { }
}
You can use the onerror of the image and show an alternative image if not loaded.
Here is a basic example with one img tag, on asp.net you can place similar the onerror call
<img id="one" src="image.gif" onerror="imgError(this)">
and the javascript
function imgError(me)
{
// place here the alternative image
var AlterNativeImg = "/images/emptyimage.gif";
// to avoid the case that even the alternative fails
if(AlterNativeImg != me.src)
me.src = AlterNativeImg;
}
and live: http://jsfiddle.net/DxN69/2/
and also http://jsfiddle.net/DxN69/3/
and final: http://jsfiddle.net/DxN69/4/
on asp.net image button
you simple add the onerror="imgError(this)" on your asp.net tag as:
<asp:ImageButton ID="ImageButton1" runat="server" onclick="ImageButton1_Click" ImageUrl="image.jpg" onerror="imgError(this)" />
even if the image button is rendered as input the final result is the same.
image send from code behind
after your last update is clear that you have make a big mistake trying to send a page as an image, and you did not even change the ContentType of it. So use a handler, eg make a new handler named loadImage.ashx and there write your code as:
public void ProcessRequest(HttpContext context)
{
// this is a header that you can get when you read the image
context.Response.ContentType = "image/jpeg";
// cache the image - 24h example
context.Response.Cache.SetExpires(DateTime.Now.AddHours(24));
context.Response.Cache.SetMaxAge(new TimeSpan(24, 0, 0));
// render direct
context.Response.BufferOutput = false;
// load here the image as you do
....
// the size of the image
context.Response.AddHeader("Content-Length", imageData.Length.ToString());
// and send it to browser
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
and your call will be something like:
<asp:ImageButton CssClass="imagetest" AlternateText=" " ID="Image1" name="mybutton" runat="server" Width="140" Height="140" CommandName="image" OnLoad="changeImage();" CommandArgument="image" CausesValidation="false" ImageUrl='<%# "loadImage.ashx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>'
now here you can double check if the image exist and send some default image if not exist.
<img src="images.png" onerror="this.onerror=null;this.src='default.png'">
I would preffer to set imageURL property for the default image you want to display. If the image is exists in database record then replace the imageURL with that record else keep it as it is.
Just do using onerror event
<img src="image.gif" onerror="alert('The image could not be loaded.')">
Instead of creating a server side image button why you just not create an html image with a link, that acts as an image button.
<a class="info" href="#">
<img src="<%# GetImage.aspx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>" onerror="this.src='<%=Page.ResolveClientUrl("~/images/emptyimage.gif") %>'" alt="" class="imagetest" />
</a>