ASP-DropDownList CodeBehind images - html

All I ever wanted is my DropDownList to be special. :(
I can write just names, but that won't be as intresting. So I tried to add images, like so:
// Somewhere in the code...
ListItem item = new ListItem();
item.Value = // something
item.Text = "<img src=\"" + <AnImagePathIGetFromTheDatabase> + "\">";
<MyDropDownlist>.Items.Add(item);
However the evil thing escapes the text in a list automatically, like so:
<img src="https://41.media.tumblr.com/bcb96f4a4c46a1001118ee216d7abacf/tumblr_mgfhbngsDl1r58qimo1_500.png">
So I get text instead of an image. How can I overcome this?
EDIT: Using Lajos' solution, I've got to a situation where I inspect the selection element, And I get the following :
<img src="http://i.somethingawful.com/u/robtg/Fiesta/f05.jpg" alt="monster" height="42" width="42">
Which is pretty much what I was looking for. Sadly, in the page source, I get the following:
<option value="MeaninglessImp" class="imageconverter">http://i.somethingawful.com/u/robtg/Fiesta/f05.jpg</option>
The list itself shows 2 empty cells. The inspector says the pictures have been scaled down to 0x0.
Fiddle: here.
Why does that happen?

You can set the Text to contain the source and not show them until the page is loaded. You can implement a Javascript library which replaces src text with images in your list. That should solve the problem.
// Somewhere in the code...
ListItem item = new ListItem();
item.Value = // something
item.Text = <AnImagePathIGetFromTheDatabase>;
listItem.Attributes.Add("class", "imageconverter");
<MyDropDownlist>.Items.Add(item);
And in Javascript you need something like:
$(function() {
$(".imageconverter").each(function() {
$(this).html('<img src="' + $(this).text() + '">');
});
});

Related

Angular variable output if/else HTML output not working

I'm confused. I'm trying to check in a loop if the outputted key is a mail key, if yes, I want to wrap the output into a <a> tag to make the email clickable. Somehow it's not working and it's printing the whole content inside the div:
<div>{{contactInfo.key === 'mail_outline' ? '' + contactInfo.value + '' : contactInfo.value}}</div>
Current result on the page:
{{contactInfo.key === 'mail_outline' ? '' + contactInfo.value + '' : contactInfo.value}}
I'm not sure if I understood the whole thing correctly. I'm coming from PHP and there I can do something like this. Can someone please explain me my issue?
If you surround the html elements inside the div with quotes like you did, you are telling angular that the divcontent is actually a text value. So it will end up displaying your condition as text.
You can add dynamic html by binding to innerHtml property like suggested, however I find it cleaner to keep display logic in the template using one of the options below. Besides, they will avoid the extra overhead of calling a function every round of change detection
*ngIf
<div >
<a *ngIf="contactInfo.key === 'mail_outline'" href="{{contactInfo.value}}">{{contactInfo.value}}</a>
<ng-container *ngIf="contactInfo.key !== 'mail_outline'">{{contactInfo.value}}</ng-container>
</div>
Or use *ngSwitch, which will be more adequate if you've got several different cases
<div [ngSwitch]="contactInfo.key">
<a *ngSwitchCase="'mail_outline'" href="{{contactInfo.value}}">{{contactInfo.value}}</a>
<ng-container *ngSwitchDefault>{{contactInfo.value}}</ng-container>
</div>
Use angular Html binding. Update your html
<div [innerHtml]="getLink()"></div>
In your typescript
getLink(){
if(this.contactInfo.key === 'mail_outline')
{
return `<a href='${this.contactInfo.value}'>${this.contactInfo.value}</a>`;
}
else
{
return this.contactInfo.value;
}
}
Thanks.

Using an image map and a link on the same image

I have images with dynamically generated image maps. I want users to be able to click on the map and be taken through to the <area href= property.
However, when they click on the background (i.e. not in any of the map's areas) I want them to go through to a background URL.
So my code looks something like this (fiddle):
<a href="fromAnchor.html" target="_blank">
<img src="image.png" usemap="#test" />
</a>
<map name="test" id="test">
<area href="fromMap.html">
</map>
In Chrome/FX it works as I expect - if I click in the area tag's shape I get taken to fromMap.html, if I click elsewhere I get directed to fromAnchor.html.
However, in IE (tested up to IE10) clicking on the img but outside the area does nothing. It does show the URL hint in the bottom left corner, but it doesn't follow the a tag.
Is there a way around this?
I came up with a solution, but it's kind of awful (so would be very happy to see a better answer).
My workaround is to dynamically add a fallback <area> that fills the entire image and let clicks outside the exiting area's fall back to it:
var msie = /MSIE/.test(navigator.userAgent);
if (msie)
{
// Don't do this hack twice
$('map[data-iehack!="1"]').each(function ()
{
// First find the image this map applies to
var $this = $(this);
var name = $this.attr('name');
var $img = $('img[usemap="#' + name + '"]');
// Then find if the image is in an <a> tag
var $link = $img.parents('a');
if ($link.length > 0)
{
// If there is an <a> add an extra <area> that fills the image
var wrapLink = $link[0].href;
var width = $img.width();
var height = $img.height();
var $fallbackArea = $('<area shape="rect" coords="0,0,' + width + ',' + height + '" />');
$fallbackArea.attr('href', wrapLink);
$this.append($fallbackArea);
}
// Flag this map so we don't add it again
$this.attr('data-iehack', '1');
});
}
This example is in jQuery but the principal should work in other frameworks.
There has to be a better way than this - and this hack has to check the browser as I can't figure out how to detect IE's failure here.

Show image icon before the link text

I am adding the link button and a image logo with that link dynamically from code behind. On the page it is showing linktext and then the image '[LinkText][Image]'. I want to show in the other manner like '[Image][LinkText]'. How we can implement it, please help.
Here is my code snippet:
HtmlGenericControl imgToAdd = new HtmlGenericControl("img");
imgToAdd.Attributes.Add("src", "../Images/Click.png");
imgToAdd.Attributes.Add("id", "img" + containerCountForLabels);
imgToAdd.Style.Add("height", "16px");
imgToAdd.Style.Add("vertical-align", "top");
HtmlGenericControl linkToAdd = new HtmlGenericControl("a");
linkToAdd.Attributes.Add("id", "linkbtn" + containerCountForLabels);
linkToAdd.Style.Add("margin-bottom", "5px");
linkToAdd.Style.Add("margin-top", "6px");
linkToAdd.Style.Add("margin-left", "10px");
linkToAdd.Style.Add("margin-right", "10px");
linkToAdd.Style.Add("font-size", "13px");
linkToAdd.Style.Add("float", "left");
linkToAdd.Style.Add("cursor", "pointer");
linkToAdd.Style.Add("color", "white");
linkToAdd.Style.Add("text-decoration", "underline");
linkToAdd.Style.Add("vertical-align", "top");
linkToAdd.Attributes.Add("onclick", "ShowHideDiv('img" + containerCountForLabels + "','divMain" + containerCountForLabels + "');");
linkToAdd.InnerText = dtReportLocal.Rows[0]["SubExpenseName"].ToString();
linkToAdd.Controls.Add(imgToAdd);
divForLink.Controls.Add(linkToAdd);
containerCountForLabels++;
I dont know why it shows before, but what you can do is to add the image and text as an innerHTML of the link instead using InnerText, something like the code below:
linkToAdd.InnerHTML = "<img src='../Images/Click.png' id='img"+ containerCountForLabels+"' style='height:16px;vertical-align:top;'>"+dtReportLocal.Rows[0]["SubExpenseName"].ToString();

Encode WhiteSpace in Razor Dynamic Attributes

I have dynamic HTML attributes generated using Razor.
Everything seems to work fine except when I generate an attribute value with a whitespace within like:
item.Name = "Organisation Structure";
When I then try to render this value in a dynamic attribute, Razor thinks that the text after the whitespace is another entirely different attribute.
<a href="#item.Url" #(!item.HasSubItems ? "data-tab-title=" + item.Name : "")></a>
Which renders wrongly as:
instead of like this:
I have even tried to use Html.Encode(item.Name) like below:
<a href="#item.Url" #(!item.HasSubItems ? "data-tab-title=" + Html.Encode(item.Name) : "")></a>
Please, any solutions to this problem will be highly appreciated.
I solved the problem by simply doing a String.Replace("","&nbsp")
<a #(!item.HasSubItems ? "data-tab-title=" + item.Name.Replace(" ","&nbsp") : "") href="#item.Url" ></a>
This solved the problem rather nicely.
You could try :
#{
var dynamicLink = string.Format("<a href='{0}' {1}></a>", item.Url, (!item.HasSubItems)? "data-tab-title='" + item.Name +"'" : "");
}
#Html.Raw(dynamicLink)

Make anchor links refer to the current page when using <base>

When I use the HTML <base> tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to set the base URL that would still allow anchor links to refer to the currently open page?
For example, if I have a page at http://example.com/foo/:
Current behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/#baz" -->
Desired behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
I found a solution on this site: using-base-href-with-anchors that doesn't require jQuery, and here is a working snippet:
<base href="https://example.com/">
/test
Anchor
Or without inline JavaScript, something like this:
document.addEventListener('DOMContentLoaded', function(){
var es = document.getElementsByTagName('a')
for(var i=0; i<es.length; i++){
es[i].addEventListener('click', function(e) {
e.preventDefault()
document.location.hash = e.target.getAttribute('href')
})
}
})
Building upon James Tomasino's answer, this one is slightly more efficient, solves a bug with double hashes in the URL and a syntax error.
$(document).ready(function() {
var pathname = window.location.href.split('#')[0];
$('a[href^="#"]').each(function() {
var $this = $(this),
link = $this.attr('href');
$this.attr('href', pathname + link);
});
});
A little bit of jQuery could probably help you with that. Although base href is working as desired, if you want your links beginning with an anchor (#) to be totally relative, you could hijack all links, check the href property for those starting with #, and rebuild them using the current URL.
$(document).ready(function () {
var pathname = window.location.href;
$('a').each(function () {
var link = $(this).attr('href');
if (link.substr(0,1) == "#") {
$(this).attr('href', pathname + link);
}
});
}
Here's an even shorter, jQuery based version I use in a production environment, and it works well for me.
$().ready(function() {
$("a[href^='\#']").each(function() {
this.href = location.href.split("#")[0] + '#' + this.href.substr(this.href.indexOf('#')+1);
});
});
You could also provide an absolute URL:
<base href="https://example.com/">
test
Rather than this
test
I'm afraid there is no way to solve this without any server-side or browser-side script. You can try the following plain JavaScript (without jQuery) implementation:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
element.href = location.href + element.getAttribute("href");
}
});
<base href="https://example.com/">
/test
#test
It also works (unlike the other answers) for dynamically generated (i.e. created with JavaScript) a elements.
If you use PHP, you can use following function to generate anchor links:
function generateAnchorLink($anchor) {
$currentURL = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped = htmlspecialchars($currentURL, ENT_QUOTES, 'UTF-8');
return $escaped . '#' . $anchor;
}
Use it in the code like that:
baz
To prevent multiple #s in a URL:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
my_href = location.href + element.getAttribute("href");
my_href = my_href.replace(/#+/g, '#');
element.href = my_href;
}
});
My approach is to search for all links to an anchor, and prefix them with the document URL.
This only requires JavaScript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery, etc.
document.addEventListener('DOMContentLoaded', function() {
// Get the current URL, removing any fragment
var documentUrl = document.location.href.replace(/#.*$/, '')
// Iterate through all links
var linkEls = document.getElementsByTagName('A')
for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
var linkEl = linkEls[linkIndex]
// Ignore links that don't begin with #
if (!linkEl.getAttribute('href').match(/^#/)) {
continue;
}
// Convert to an absolute URL
linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
}
})
You can use some JavaScript code inside the tag that links.
<span onclick="javascript:var mytarget=((document.location.href.indexOf('#')==-1)? document.location.href + '#destination_anchor' : document.location.href);document.location.href=mytarget;return false;" style="display:inline-block;border:1px solid;border-radius:0.3rem"
>Text of link</span>
How does it work when the user clicks?
First it checks if the anchor (#) is already present in the URL. The condition is tested before the "?" sign. This is to avoid the anchor being added twice in the URL if the user clicks again the same link, since the redirection then wouldn't work.
If there is sharp sign (#) in the existing URL, the anchor is appended to it and the result is saved in the mytarget variable. Else, keep the page URL unchanged.
Lastly, go to the (modified or unchanged) URL stored by the mytarget variable.
Instead of <span>, you can also use <div> or even <a> tags.
I would suggest avoiding <a> in order to avoid any unwanted redirection if JavaScript is disabled or not working, and emulate the look of your <a> tag with some CSS styling.
If, despite this, you want to use the <a> tag, don't forget adding return false; at the end of the JavaScript code and set the href attribute like this <a onclick="here the JavaScript code;return false;" href="javascript:return false;">...</a>.
From the example given in the question. To achieve the desired behavior, I do not see the need of using a "base" tag at all.
The page is at http://example.com/foo/
The below code will give the desired behaviour:
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
The trick is to use "/" at the beginning of string href="/bar/".
If you're using Angular 2 or later (and just targeting the web), you can do this:
File component.ts
document = document; // Make document available in template
File component.html
<a [href]="document.location.pathname + '#' + anchorName">Click Here</a>