How do I add custom hyperlinks to a webpage - asp.net

I want to add a hyperlink to a social bookmarking site om my webpage which requires me to include the name of the page it is being sent from.
Example of what I am trying to achieve:
Current page is:
http://www.testpage.com/testpage.aspx?test=34
Hyperlink I want to create on the above page:
http://www.stumbleupon.com/submit?url=http://www.testpage.com/testpage.aspx?test=34
What is the easiest way to programmatically add this customised hyperlink to a webpage?

Assuming that you have a hyperlink like that :
<asp:HyperLink runat="server" ID="myLink" Text="stumbleupon"></asp:HyperLink>
At server side :
string currentPagesUrl =
HttpUtility.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri);
myLink.NavigateUrl = string.Format("http://www.stumbleupon.com/submit?url={0}",
currentPagesUrl);
Or an alternative way (this one is easier I think) :
<a href="http://www.stumbleupon.com/submit?url=<%= HttpUtility.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri) %>" target="_blank">
stumbleupon 2</a>

I second Canavar's answer. You might want to also URL encode the currentPagesUrl string when building the hyperlink:
myLink.NavigateUrl = string.Format("http://www.stumbleupon.com/submit?url={0}",
Server.UrlEncode(currentPagesUrl));

Using jQuery:
$(document).ready(function(){
$("a.stumblethis").each(function(){
$(this).attr("href", "http://www.stumbleupon.com/submit?url="+$(this).attr("href"));
});
});
This will convert all links that have a class of "stumblethis".

Related

How do I edit values in a web-browser. .NET

<a id="ctl00_ctl00_cphBanner_BannerAlertsLoginView_BannerAlerts_Authenticated_rbxBanner​Alert_rbxAlerts_RobuxAlertCaptionHyperLink" class="RobuxAlertCaption tooltip-bottom" href="AccountBalance.aspx" original-title="ROBUX">740</a>
How do I edit the 740. For example, If button1 is pressed then. 740 textbox1.text.
How do I edit the webbrowser HTML with the text box value
Try this
JQUERY
$("#<%= txtName.ClientID%>").val("Test");
If if you want to do it after postback, There is a few solution
Make your tag as .net registered;
<a id="hrefReplace" runat="server"></a>
And change attribute like
hrefReplace.Width = 775;
Post a Javascript to your App
string jScript;
jScriptValidator="<script> $("#<%= txtName.ClientID%>").widht(775);)";
Page.RegisterStartupScript("regJSval",jScriptValidator);

URL Referer not working on pop up windows

I have two pages namely www.abc.com/pg1.aspx and www.abc.com/pg2.aspx
pg1.aspx
response.redirect("www.abc.com/pg2.aspx");
pg2.aspx
string url_refer = Request.UrlReferrer.ToString();
UrlReferrer is working fine.
pg1.aspx
<a href='#' onclick=\"window.open('www.abc.com/pg2.aspx', 'windowname2', 'width=1014, height=709, screenX=1, left=1, screenY=1, top=1, status=no, menubar=no, resizable=no, toolbar=no'); return false;\">
pg2.aspx
string url_refer = Request.UrlReferrer.ToString();
UrlReferrer is NULL
I googled for the solution. but none of them are leading to the solution i want.
My problem is if the window is with no menubar, status or toolbar, UrlReferrer is NULL
if not, UrlReferrer has the previous page's URL.
I also tried url_refer = Request.ServerVariables["HTTP_REFERER"].ToString(); instead of string url_refer = Request.UrlReferrer.ToString();.
the result is the same.
Any solution?
My solution is to take it from "document.referrer"
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('hfUrlReferrer').value = document.referrer;
})
<a href="javascript:void(0);" onClick="MyWindow=window.open('','gallery','location=no,directories=no,menubar=no,scrollbars=no,width=550,height=550');MyWindow.location.href='yoururl.html;MyWindow.focus(); return false;">
The trick is to use location.href which does record the referer in IE.
I found this great workaround on a forum, and adapted it slightly.
Put this code at the top of your page:
<script language="JavaScript">
function goTo(url){
var link = document.getElementById("link");
link.href = url;
link.click();
}
</script>
<a id="link" target="_blank" href="javascript:void(0)"
style="visibility:hidden;position:absolute;"></a>
...and then build your links like this:
<input type="button" value=google onclick="goTo('http://www.google.com')">
What you're doing is creating an invisible <a> element, then using javascript to change that element's address, and programatically "click" it.
There's no easy answer to this - in general, the UrlReferrer is a browser-specific behaviour. Chrome, for instance, can process this differently than Internet Explorer.
If you are doing the referring yourself then you'll be best off passing a querystring parameter or using session state to identify the referring URL.
I'm not sure.. but I found out..
Session is not working if we call a new page using Javascripts.
I was told that all session values are reset on a new page which is called using javascripts.
As an alternative for my question, I used QueryString.
I really don't want the users to see the URL but I already hide the URL with javascript.
So, I have no problem using querystring, right?
Does anyone hava a better solution?

How can I add a random number to an ASP.NET menu item url on each click

One step to prevent caching (in addition to adding the appropriate headers etc..) is to add a random number to the end of my URLs.
I'm using an ASP.NET menu and would like to add a random number to each menu item's navigate URL as it is clicked.
I can do this in the MenuItemDataBound event, but haven't had much luck doing the same with the MenuItemClicked Event.
Answer (can't answer my own question for 8 hours, and I don't have time to wait that long so here's my server side solution.)
To do this server side, I've had to remove the sitemap and the databinding from the menu.
I simply added all of the items from the sitemap as menuitems to the items collection in the menu markup removing the url property. The key here is removing the url property.
<asp:menu>
<items>
<asp:menuitem Text="Home" ToolTip="Go Home" Selectable="True" />
</items>
</asp:menu>
Then in your code behind you can handle the MenuItemClicked event (which should now fire, because there is no longer a navigateurl in the markup).
In the MenuItemClicked event codebehind I simply do the following:
string TimeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
// get iframe control - must have 'runat=server' attribute
HTMLControl display = CType(this.FindControl("display"), HTMLControl);
// dispatch menuitem
switch (e.item.valuepath)
{
case "Home":
display.attributes("src") = "home.aspx?=" + TimeStamp()
break;
.
.
.
}
This is the server side solution with an iframe.
I don't know if you're considering client-side URL manipulation as an option, but running this little bit of JavaScript on each page load would give you the behavior you're looking for by appending a timestamp to each of the links. You can modify it to target links in a specific area/div of the site, but this example will change them all:
<!-- include the jQuery library -->
<script type="text/javascript">
$(function(){
var time = new Date().getTime();
$('a').each(function() {
var append = (this.href.indexOf('?') > -1 ? '&' : '?');
$(this).attr('href', this.href + append + 't=' + time.toString());
});
});
</script>
Since every time the page loads the timestamp will be different, you should always get a unique set of links.
EDIT Here's a working jsFiddle demoing the behavior: http://jsfiddle.net/2HzqU/2/
I don't think that's the best solution. Have you tried using something like this:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

Wanting to use an image with text in Html.ActionLink

I am using the following:
<img src="../../Content/Images/lock_16.gif" />
#Html.ActionLink("Register",
"Register",
"Users",
null,
new { title = "Register your ID", rel = "nofollow"
})
What I would like is for the lock image to appear inside of the <a> </a> so it is clickable and not before it. I already use (and change color on hover) of a background image so its not possible for me to use the background-image property to display the image.
Can anyone think of a way that I can set the image so that it will show before the text and still be clickable. Hopefully I can find a way that still allows me to use the MVC Html.ActionLink.
Html helpers in ASP.NET MVC should be used when they simplify writing code, not always. Plain html would go way better in your case
<a href="#Url.Action("Register", "Users")" title="Register Your ID", rel="nofollow">
Register <img src="#Url.Content("~/Content/Images/lock_16.gif")" />
</a>
Note that link address is still generated dynamically, using UrlHelper.Action method. This way, you do not lose link dependency to your route configuration. Also, as Nicholas mentioned, image source should be generated via Url.Content helper.
You may use something like -
#Html.ActionLink("link Name", "Action Method", "Controller", new { style = "background-image:url('.././Images/imageName.png')" },null)
#Html.ActionLink("link Name", "Action Method", "Controller",
new { style = "background-image:url('.././Images/imageName.png')" },
null)

Javascript Rich Display WYSIWYG Component/Methodology

quick back story--
I am working on ASP.Net based template editor that lets authors create text templates using Javascript inserted placeholder tags that will be filled in with dynamic text when the templates are used to display the final results.
For example the author might create a template like
The word [%12#add] was generated dynamically.
The application would eventually replace the tag with a dynamic word down the road (though it's not specifically relevant to this post)
The word foo was generated dynamically.
Depending on the circumstances, the template may be created in a text input, textarea or a modified version of the Ajax Control Toolkit HTML Editor. There might be 40 or more of these editable elements on the page, so using lots of stripped down or modified HTML editors would probably bog the page down too much.
The problem is that the tags such as [%12#add] are displayed inline with the user text and the result is confusing and aesthetically gross. The goal is parse the contens of the source element and when a tags such as [%12#add] are encountered, display something prettier and less cryptic to the user such as a stylable element or image wherever tags such as [%12#add] occur. The application still needs the template text with the tags on postback.
So the user might see
The word tag placeholder was generated dynamically.
but the original template would still be the value of the text input box
The word [%12#add] was generated dynamically.
It seems HTML editors like the ACT version and FckEditor accomplish this by rendering their output in an IFrame, but rather than kill myself trying to roll a lighter specialized version myself, I thought I'd ask if anyone knows of an existing free component or approach that has already tackled this.
With good reason, I don't think S.O. allows HTML formatting, but the bold "tag placeholder" above would ideally be something like tag placeholder.
I think CKEditor might be your best bet. I recently wrote a plugin for it that kept placeholders in the editable content for chunks of content that the user couldn't edit directly. A question I asked may help, particularly the comments to the accepted answer: Update editor content immediately before save in CKEditor plug-in.
The recommendation to me was to look at how object tags (e.g. as used to embed Flash movies) are handled, and from that I was able to proceed fairly quickly. Be aware though that CKEditor is not well documented for plugin developers, so you may often have to resort to looking at the source code.
Final model solution in case someone in the same situation needs a boost.
aspx page:
<div>
<asp:TextBox runat="server" ID="txtTest" TextMode="MultiLine" CssClass="Over" />
<br />
Add CKEdit
<br />
Add Tag
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</div>
<script type= "text/javascript" >
<!--
function ckTest(el) {
var tinyTool = {
toolbar:
[
['Bold', 'Italic', 'UIColor'], ['Styles', 'Format', 'Font', 'FontSize']
]
};
//Note: config.htmlEncodeOutput = true; to work with ASP.NET, see postback for decoding input
var editor = CKEDITOR.replace(el);//, tinyTool);
editor.addCss('.aux1 { background-color: #FFE0C0; border: solid 1px #17659E; }');
}
function insertTag(id, tag, display) {
var e = CKEDITOR.instances[id];
if (e) {
//Storing in comments does not work. stripped out when using insertHtml. Workaround?
//e.insertHtml("<span class='aux1'>" + display + "<!--" + tag + "--></span>");
//Kludge: fake attribute
e.insertHtml("<span class='aux1' tag='" + tag +"'>" + display + "</span> ");
}
}
-->
</script>
-->
</script>
CodeBehind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Note: CKEditor converts single to double quotes in insertHtml
Regex regHiddenTag = new Regex(#"<span\sclass=""\w+""\stag=""(\[%[0-9]{1,2}_[TR]\])"">\w+</span>");
//Note: config.htmlEncodeOutput = true;
string encoded = txtTest.Text
.Replace("<", "<").Replace(">", ">").Replace("&", "&");
//TODO: Use AntiXss Library that I have to thwart bad HTML
string extractedTag = regHiddenTag.Match(encoded).Groups[1].Value;
//store to DB
string template = regHiddenTag.Replace(
encoded,
extractedTag);
//repopulate
string finalText = template.Replace(extractedTag, "foo");
}

Resources