Alternate image display in asp.net - c#

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>

Related

I make fileUpload to save images in folder now i want to display it

That is the code to get url of image from the folder
<asp:Repeater ID="rptImages" runat="server">
<ItemTemplate>
<li>
<img alt="" style='height: 75px; width: 75px' src='<%# Eval("Images") %>' />
</li>
</ItemTemplate>
</asp:Repeater>
This do display images
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images"));
List<String> images = new List<string>(filesindirectory.Count());
foreach (string item in filesindirectory)
{
images.Add(String.Format("~/Images/{0}", System.IO.Path.GetFileName(item)));
}
rptImages.DataSource = images;
rptImages.DataBind();
when i run it it says:" An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. "
and show :( List<String> images = new List<string>(filesindirectory.Count());) in red
What should i do?
I have not encountered error you mentioned, but I found another error on the binding.
Here you should change the binding using Container.DataItem and since you are using ~ for the path you should add runat="server" like mentioned in this link.
<img alt="" style='height: 75px; width: 75px' src='<%# Container.DataItem %>' runat="server"/>

How to bind images from TreelistEx to a repeater in Sitecore

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>

Showing Byte Image in repeater

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")) %>' />

Why using IHttpHandler causes my submit button to open to the new window

<asp:Panel ID="pnlSearch" runat="server" DefaultButton="btnValidateName">
<div class="spPad">
<b class="userLabel">Enter Full/Partial First or Last Name to Search (Leave blank for all):</b>
</div>
<div class="spPad" style="text-align: right;">
<asp:TextBox ID="txtName" Width="95%" runat="server" ClientIDMode="Static"></asp:TextBox>
</div>
<div class="spPad" style="text-align: right;">
<asp:Button ID="btnValidateName" CssClass="orange button" runat="server" Text="Validate Name" onclick="btnValidateName_Click" />
</div>
<div class="spPad" style="text-align: right;">
<asp:Label runat="server" Text="" ID="lblIsValid"></asp:Label>
</div>
</asp:Panel>
After searching and displaying the result inside a repeater, I allow user to view the file in the browser by opening a new window by clicking on a linkbutton:
<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
The code behind is this:
protected void ViewFile(object sender, EventArgs e)
{
Response.Redirect("OpenFilePDF.ashx?fileVar=" + Session["fileName"]);
}
The OpenFilePDF.ashx code is:
public void ProcessRequest (HttpContext context) {
System.Web.HttpRequest request2 = System.Web.HttpContext.Current.Request;
string strSessVar2 = request2.QueryString["fileVar"];
try
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
byte[] fileByteArray = File.ReadAllBytes(Path.Combine(#"C:\PDF", strSessVar2));
response.AddHeader("Content-disposition", String.Format("inline; filename={0}", strSessVar2));
response.BinaryWrite(fileByteArray);
response.End();
}
catch (Exception ce)
{
}
}
public bool IsReusable {
get {
return false;
}
}
The scenario that is happening is, after the search and displaying the result, if the user clicks on the View in Browser button and comes back to the old window and clicks on the Validate Name button the result goes in the window that was originally opened by clicking on View in Browser button instead of running the search on the current window. I have to refresh the page for it to search on the current window again, even if the new window was already opened.
How do I resolve the issue I am having?
Your View in Browser is implemented as
<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
On the client click, the form element of your web page will look like
<form ... target="_blank">
Causing any submit of the form to open in a new window. However, every single postback to ASP.NET constitutes a submission of your form, so everything will open in a new window. Rather than setting the target attribute on the form, you might consider setting the attribute just on the link. To do that, see this answer:
https://stackoverflow.com/a/2637208/1981387
Keep in mind, you will have to use a HyperLink instead of a LinkButton. Actually, this will benefit you by reducing the round trip back to your server by 1, because you are using the LinkButton to redirect to another url anyways. So your HyperLink can just have an href that points to "OpenFilePDF.ashx?fileVar=" + Session["fileName"] to begin with.
Edit/TL;DR:
Change
<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
To
code-behind:
public string FileLocation
{
get
{
return "OpenFilePDF.ashx?fileVar=" + Session["fileName"];
}
}
protected void Page_Load(object sender, EventArgs e)
{
...
lnkViewProper.NavigateUrl = FileLocation;
...
}
markup:
<asp:HyperLink
ID="lnkViewProper"
Text="View in Browser"
runat="server"
Target="_blank" />

Fetching photos dynamically?

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
}

Categories