Setting background image in a repeater - c#

I am trying to set a background image in a repeater programmatically. Variations of the following have not worked, including trying to set the url in the div, not the jquery function:
The JQuery function:
var getBackgroundImage = function (imagePath) {
var backgroundImage = 'url(' + iipServ + '?FIF=/IIPServer/images/' + imagePath + '&WID=40&CVT=PNG' + ')';
return backgroundImage;
};
The ASP page:
<asp:Repeater ID="docResults" runat="server" ItemType="ArchiveViewer.Models.Document"
SelectMethod="GetSearchResults" >
<ItemTemplate>
<div class="result" data-docid="<%#:Item.DocumentId %>"
data-imageDir="<%#:Item.FolderPath %>"
data-objData="<%#:Item.JSONPath %>"
style="<%= getBackgroundImage(Item.Pages.First().ImagePath) %> ">
<%#:Item.Metadata.Title %>
</div>
</ItemTemplate>
</asp:Repeater>
Can this be done? How?
Thank you!
EDIT: Each div has its own image. I'm getting the URL from the server.
EDIT 2: I am not instead of using a jquery function, am using a web method in my code behind:
[WebMethod]
public string getBackgroundImage(string path)
{
string iipServer = ConfigurationManager.ConnectionStrings["iipServer"].ConnectionString;
string urlString = "background-image : url('" + iipServer + "?FIF=/IIPServer/images/" +
path + "&WID=40&CVT=PNG)'";
System.Diagnostics.Debug.WriteLine(urlString);
return urlString;
}

In the ASPX page:
style="background-image : <%=getBackgroundImage(Item.Pages.First().ImagePath) %>">
In the code behind:
public string getBackgroundImage(string iipServ, string path)
{
return "url('" + iipServ + "?FIF=/IIPServer/images/" + path + "&WID=40&CVT=PNG)'";
}
It's not clear what iipServ is and where to take it from. Just pass it to the C# function along the path.
You should remove the JS function, this will be all server-side.

pid: Your answer is almost correct, but the compiler didn't like it. It helped me figure out how to do it correctly, though. Thank you.
In case it helps someone else, here is how I fixed this issue:
My ASPX page:
<ItemTemplate>
<div class="result" data-docid="<%#:Item.DocumentId %>"
data-imageDir="<%#:Item.FolderPath %>" data-objData="<%#:Item.JSONPath %>"
style="<%#: getBackgroundImage(Item.Pages.First().ImagePath) %>" >
<%#:Item.Metadata.Title %>
</div>
</ItemTemplate>
And my code behind:
[WebMethod]
public string getBackgroundImage(string path)
{
string iipServer = ConfigurationManager.ConnectionStrings["iipServer"].ConnectionString;
string urlString = #"background-image:url("
+ iipServer + "?FIF=/IIPServer/images/" +
path + "&WID=40&CVT=PNG)";
return urlString;
}

Related

Remove Span tag generated in asp.net text label

I cannot remove the span tag which auto generated with the image tag.
Asp.net Code :
if (!IsPostBack)
{
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
SiteManagementService siteMng = new SiteManagementService();
LogedUserDTO logedUser = siteMng.GetLogedUserByUserId(Session["UserLoginID"].ToString().Trim());
LabelUser.Text = logedUser.FullName + " | " + logedUser.Company.CompanyDesc;
**LabelImage.Text = "<img src=\"" + siteMng.GetUserImageUrl() + logedUser.ProfileImage + "\" class='img-avatar' />";**
LabelDatetime.Text = DateTime.Now.ToString();
Session["UserAccessLevel"] = logedUser.UserGroupId;
Session["UserCompanyId"] = logedUser.CompanyId;
RepeaterMenu.DataSource = siteMng.GetMenuByUserGroup(logedUser.UserGroupId);
RepeaterMenu.DataBind();
LabelMasterFooter.Text = "© 2013 " + ResourceData.CompanyName + ". All rights reserved.";
}
Front End Code :
<asp:Label ID="LabelImage" runat="server" ></asp:Label>
Generated HTML Code :
<span id="ContentPlaceHolderHeader_LabelImage"><img src="UploadedFiles/ProPicturs/Img_1711.JPG" class="img-avatar"></span>
Code i want is just
<img src="UploadedFiles/ProPicturs/Img_1711.JPG" class="img-avatar">
If you want to only use an image tag, there is an Image tag in asp.net
protected string image_tag; // add this var in your page class and set it as protected
...
if (!IsPostBack)
{
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
SiteManagementService siteMng = new SiteManagementService();
LogedUserDTO logedUser = siteMng.GetLogedUserByUserId(Session["UserLoginID"].ToString().Trim());
LabelUser.Text = logedUser.FullName + " | " + logedUser.Company.CompanyDesc;
image_tag = "<img src=\"" + siteMng.GetUserImageUrl() + logedUser.ProfileImage + "\" class='img-avatar' />";
LabelDatetime.Text = DateTime.Now.ToString();
Session["UserAccessLevel"] = logedUser.UserGroupId;
Session["UserCompanyId"] = logedUser.CompanyId;
RepeaterMenu.DataSource = siteMng.GetMenuByUserGroup(logedUser.UserGroupId);
RepeaterMenu.DataBind();
LabelMasterFooter.Text = "© 2013 " + ResourceData.CompanyName + ". All rights reserved.";
}
you can try to use in .aspx page.
<%= image_tag %>
instead of
<asp:Label ID="LabelImage" runat="server" ></asp:Label>
A Label Control will add a HTML element to the page. Either as a div or a span element. So this
<asp:Label ID="Label1" runat="server" CssClass="MyLabel">
Content...
</asp:Label>
Becomes this
<span id="Label1" class="MyLabel">
Content...
</span>
But a PlaceHolder does not generate it's own html element. So the following code
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
Content...
</asp:PlaceHolder>
Will generate
Content...
But there are some downsides, as a PlaceHolder does not have a CssClass property.

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

Href Link Code Behind

I am trying to add a a link as part of the Product.Text but I've horribly got it wrong here, doing this on the C-Sharp code behind.
tcProduct.Text = "<div class=\"productname\">" + "<a class=\"productnameLink\" href=\"item.Product.Url\">" + item.Product.Name + "</a>" + "</div>";
The backward slashes are beginning to confuse me. Instead of a normal hyperlink i guess i should be using the .NET hyperlink instead??
I've tried this but doesn't add the hyperlink;
HyperLink productNameLink = new HyperLink();
productNameLink.Text = "<div class=\"productname\">" + item.Product.Name + "</div>";
productNameLink.NavigateUrl = item.Product.Url.ToString();
productNameLink.CssClass = "prodNameLink";
tcProduct.Controls.Add(productNameLink);
Plain string formatting should do the trick:
tcProduct.Text = string.Format("<div class=\"productname\"><a class=\"productnameLink\" href=\"{0}\">{1}</a></div>",
item.Product.Url, item.Product.Name);
However, you really better use a Repeater which is meant exactly for such things. Markup:
<asp:Repeater ID="rptProducts" runat="server">
<HeaderTemplate><h1>Products</h1></HeaderTemplate>
<ItemTemplate>
<div class="productname"><a class="productnameLink" href="<%# Eval("Url") %>"><%# Eval("Name") %></a></div>
</ItemTemplate>
</asp:Repeater>
And in the code behind:
rptProducts.DataSource = arrProducts;
rptProducts.DataBind();
Where arrProducts is the collection of your products.
What i used to do that is ASP Literal.
<asp:Literal ID="Literal2" runat="server"></asp:Literal>
Then in the code set to it with
Literal2.Text = "<a class='productnameLink' href=" + item.Product.Url + ">" + item.Product.Name + "</a>"
You can use Panel control which renders as div.
var link = new HyperLink
{
Text = item.Product.Name,
NavigateUrl = item.Product.Url.ToString(),
CssClass = "prodNameLink"
};
var panel = new Panel
{
CssClass = "productname"
};
panel.Controls.Add(link);
tcProduct.Controls.Add(panel);
Output:
<div class="productname">
<a class="prodNameLink" href="http://www.google.com">Google</a>
</div>
The Text property is supposed to be text only.
Many ways to do what you need to, but if you want to stick to using html string you could use:
tcProduct.Controls.Add(new HtmlGenericControl
{
InnerHtml = string.Format(#"<div class=""productname""><a class=""productnameLink"" href=""{0}"">{1}</a></div>", item.Product.Url, item.Product.Name )
});
Bonus, you can get rid of the '\' escape char with averbatim string literal: #"" (you need to double the quotes).

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
}

Databind and trying to get index in Listview

Need a hand trying to get my rotating banner working properly on my website. I'm using the jquery cycle plugin which manages the rotation. Within my CMS I've got something called a smartform, which contains upto 6 pictures. The code below (something which I wrote by following a tutorial for the banner) works really well. However I would like to somehow get the index of the image and place it within the alt tags. What I am trying to achieve is the alt tag to say "Banner_(ImageIndexNumber)".
Hopefully someone can help, thanks all
C# Codebehind
private void BannerFill(int contentId)
{
try
{
uxBannerContentBlock.DefaultContentID = contentId;
uxBannerContentBlock.Fill();
string xml = uxBannerContentBlock.EkItem.Html;
SmartForm.RotatingBanner.BannerImage bannerGroup = (SmartForm.RotatingBanner.BannerImage)
Ektron.Cms.EkXml.Deserialize(typeof(SmartForm.RotatingBanner.BannerImage), xml);
List<BannerSlide> slides = GetBannerSlides(bannerGroup.Slides);
//Databind//
uxBannerRepeater.DataSource = slides;
uxBannerRepeater.DataBind();
}
catch { }
}
protected List<BannerSlide>
GetBannerSlides(SmartForm.RotatingBanner.BannerImageSlides[] bannerGroupSlides)
{
List<BannerSlide> bSlides = new List<BannerSlide>();
foreach (SmartForm.RotatingBanner.BannerImageSlides bgSlide in bannerGroupSlides)
{
bSlides.Add(new BannerSlide(bgSlide.Image.img.src));
}
return bSlides;
}
public class BannerSlide
{
//properties//
public string SlideImage { get; set; }
//constructor//
public BannerSlide(string slideImage)
{
SlideImage = slideImage;
}
}
Front end
<div class="slideshow">
<CMS:ContentBlock ID="uxBannerContentBlock" runat="server" Visible="false" />
<asp:Repeater runat="server" ID="uxBannerRepeater">
<ItemTemplate>
<img src="<%# DataBinder.Eval( Container.DataItem,"SlideImage") %>" alt="Banner_<%# Container.ItemIndex %>" />
</ItemTemplate>
</asp:Repeater>
alt='<%# "Banner_" + Container.ItemIndex %>'

Categories