I have a link like that. It's getting from instagram api.
http://localhost:60785/access_token.aspx/#access_token=43667613.4a1ee8c.791949d8f78b472d8136fcdaa706875b
How can I get this link from codebehind?
I can take it with js but i can't get it after assign to label. I mean:
<script>
function getURL(){
document.getElementById('lblAccessToken').innerText = location.href;
}
</script>
This js function is in body onload event. How can I reach this innerText value from codebehind?
If you are using ASP.NET 4.0 and jQuery, its fairly easy. Otherwise you may have to deal with mangled id and have to deal with DOMReady on your own. Try this
Markup
<asp:Label ID="lblAccessToken" runat="server" ClientIDMode="Static"></asp:Label>
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token");
$("#lblAccessToken").html( myToken );
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
You want the value on Page_Load right? I haven't figured out a way myself to fetch the hash value on Page_Load.I usually do one of these things
Pass the hash value to a jQuery ajax method and store it there.
Grab the hash value and redirect to the same page after converting it to a querystring
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token") || "";
if(my_token !=== ""){
window.location = window.location.split("/#")[0] + "?access_token=" + myToken;
}
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
Now at Page_Load, grab it like
string token = Request.QueryString["access_token"];
Please note that it takes one more round trip to the server and so not very efficient. But this is what I do.
Related
I have a img button. When it is clicked, I set the session value using jquery. however I cannot get the session on vb code behind. My process is like that after the user click the image, I set the session. When the user open popup page and return the page. I need to check the session to do something. However in the vb code, the session is nothing. Would some one tell me how to do it.
The below code call the function:
<asp:Image ID="img" runat="server" onclick="SetSession(hdID);" ImageUrl="pic_bottle.gif" />
The jquery script:
function SetSession(hdID) {
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
$.session.set('UpdateProdOrder', -1);
}
else {
var hdProdID = $('#hdProdID').val();
$.session.set("UpdateProdOrder", hdProdID);
}
alert($.session.get("UpdateProdOrder"));
}
The vb code behind never get the session
If Not Session("UpdateProdOrder") Is Nothing Then
'do something
updateOrder()
end if
The localStorage and sessionStorage properties allow saving key/value pairs in a web browser.
The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
These values are maintained on the client side, but you are trying to retrieve it on the server side. session variables are server side
Solution:
Method 1:
You'd have to have a little ajax call to talk to the server to set it.
please check it out
Method 2 :
Assigning the ASP.NET Session Variable using Javascript.
<script type="text/javascript">
function SetSession(hdID)
{
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
'<%Session["UpdateProdOrder"] = "' + -1+ '"; %>';
}
else {
var hdProdID = $('#hdProdID').val();
'<%Session["UpdateProdOrder"] = "' + hdProdID+ '"; %>';
}
alert('<%=Session["UpdateProdOrder"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetSession()
{
var updateProdOrder= '<%= Session["UpdateProdOrder"] %>';
alert(updateProdOrder);
}
</script>
You cannot change a server side Session object with javascript directly. You need to send it to the server somehow. This can be done by changing the image to an ImageButton and do a PostBack to modify the Session object. But since you seem to have some data in hdID. You cannot send that to the server with a ImageButton alone, you'll need a HiddenField
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="SetSession(hdID);"
ImageUrl="pic_bottle.gif" OnClick="ImageButton1_Click" />
<asp:HiddenField ID="HiddenField1" runat="server" />
<script type="text/javascript">
var hdID = 'test';
function SetSession(hdID) {
$('#<%= HiddenField1.ClientID %>').val(hdID);
}
</script>
And then in code behind
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Session["UpdateProdOrder"] = HiddenField1.Value;
Label1.Text = string.Format("Session value is now '{0}'", Session["UpdateProdOrder"]);
}
You could do this also without the javascript SetSession, but that depends on where and when hdID is used on other parts of the page.
I am trying to access the script variable pic and assign it to another variable in C#, say hidden field hdn. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
alert(pic);
});
});
});
</script>
There is no way to assign a C# variable by javascript.
You have to send that value from the client (where you JavaScript is running) to the Server, and assign it.
This is so called ajax request, just google it and you'll find millions of good examples of how to achieve that.
create a hidden filed and then set the value from javascript
<asp:hiddenfield id="hf_MyValue"
value="whatever"
runat="server"/>
How To Set value in javascript
//get value from hidden filed
var test= document.getElementById('<%= hf_MyValue.ClientID %>');
//set value in hidden filed
document.getElementById('<%= hfBrand.ClientID %>').value = "True";
Create a hidden variable like this,
<input type="hidden" id="hdnVariable" runat="server" />
Now try this code
<script type=\"text/javascript\">
$(document).ready(function() {
$.get('<%=completeURL%>',
function(d) {
$(d).find('entry').each(function(){
var $entry = $(this);
var pic = $entry.find('content').attr('src');
//assign value to server side hidden variable
$("#<%=hdnVariable.ClientID%>").val(pic);
});
});
});
</script>
Now you can access this hidden field from C# code like this
string pic=hdnVariable.Value;
i am working on a project in c#.net , I have a jquery code in my master page and the master page is included in my home page. I have created hyperlinks dynamically in my home page.
i want that when ever a user clicks on the hyperlink, instead of the wholepage only 1 part of the page with div class=refresh1 will reload.
i have include following jquery in my head tag.
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
var link1 = $(".mylink").text();
$.post("loaddata.aspx",
{
link: link1
},
function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("Done!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
$(".refresh1").load('loaddata.aspx .part1');
});
});
});
</script>
here mylink is class of 'a' tag.
i want that when ever the hyperlink will be clicked it will load the refresh1 class part from another page i.e from loaddata.aspx with class=part1.
in loaddata.aspx i want to retrive the value of link that i have passed in post method .how can i do it plzzzzzzzzz reply aasap.
You can use .load() like so:
$('a').click(function () {
var link1 = $(this).text();
$(".refresh1").load('loaddata.aspx .part1',{
link : link1
},function(data){
//optional callback code
});
});
the .load() fires a GET request though. To do it using POST, you must use .post() and parse the data it retrieves:
$('a').click(function () {
var link1 = $(this).text();
$.post('loaddata.aspx',{
link : link1
},function(data){
$(data).find('.part1').appendTo('.refresh1');
});
});
You can use Request["link"] to get the value.
Also make sure you decode the value after you retrieve.
i am trying to make an image gallery with pictures fading in and out. I already have that part covered, but so far im hard coding the image url's in my .aspx page. I don't want this, i need it to be dynamic.
<script type="text/javascript">
$(function()
{ var img = $("img.x");
$(img).hide().eq(0).show();
var cnt = img.length
setInterval(imgRotate, 5000);
function imgRotate() {
$(img).eq((img.length++) % cnt).fadeOut("slow",
function() {
$(img).eq((img.length) % cnt).fadeIn("slow");
});
}
});
</script>
<body>
<form id="form1" runat="server">
<div>
<img class="x" alt="Image1" src="Desert.jpg"/>
<img class="x" alt="Image1" src="Lighthouse.jpg"/>
</div>
</form>
this makes the images fade in and out, which is good, but as you can see, i've hardcoded the images in this example. I can't use this for my application.
What i want to do is the following:
i want to pass a List<string> (codebehind) to the jQuery script that will just iterate over the list and replace the source url of the image.
i just want to do something like this in the jQuery script (pseudo-code):
int counter = 0;
var img = ListFromCodeBehind[counter];
//do some fading stuff
count++;
i've tried using <%=%> server tags, and so forth but to no avail. I've read lots of things but they all seem overly complicated for what i'm trying to achieve..
Why is everybody forcing you to use AJAX? There is no need to load image list in separate HTTP request. I assume your code comes from some aspx page. Therefore you can provide a public method in this Pages's class (lets call it GetImages()) that returns a string that looks like JavaScript array. I.e.
public string GetImages()
{
return "['Desert.jpg', 'Lighthouse.jpg']";
}
Then in you JavaScript code (that is placed in this Page's aspx file as well) you can call public method of Page's class with classic ASP syntax:
int counter = 0;
var ListFromCodeBehind = <%= this.GetImages() %>;
var img = ListFromCodeBehind[counter];
//do some fading stuff
count++;
which will finally print:
var ListFromCodeBehind = ['Desert.jpg', 'Lighthouse.jpg'];
and this is the result I believe you expect.
You can add a Web Method into your aspx page (code behind) that can be called by AJAX.
Your code behind method will return a string that contains the URL to the images, in a JSON format (so that JQuery knows how to iterate though it out of the box).
Have a look at this thread to have an idea of how to create a web method in an aspx code behind file. I'd do it via asp.net MVC though...much more straightforward
Calling an ASP.NET server side method via jQuery
//Controller
[HttpGet]
public JsonResult GetImageURLS()
{
var urls = GetUrls();
return Json(new { urls = urls }, JsonRequest.AllowGet);
}
//js file
$.ajax({ url : '/GetImageURLS/', success : function(e) { if (e && e.urls) {
var $images = $(".images");
for (var i in e.urls) {
$images.append('<img src="' + i.url + '" class="x" ' + ' alt="' + i.alt + '" /> ';
}
});
//html
<div class="images">
</div>
Try this for initial load of the images. Then call your function on them after the images are populated.
You can use AJAX and call a webservice in your Javascript to return your image list as follows:
function LoadImages() {
var url;
url = "WebServices/wsImages.asmx/GetImageList"
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function (response) {
var imgList = response.d;
//Loop through image list etc.
}
});
}
My attempted methods.
Looking at the JS via browser, the #ViewBag.CC is just blank... (missing)
var c = "#" + "#ViewBag.CC";
var d = $("#" + "#ViewBag.CC").value;
var e = $("#" + "#ViewBag.CC").val();
var c = "#ViewBag.CC";
var d = $("#ViewBag.CC").value;
var e = $("#ViewBag.CC").val();
if you are using razor engine template then do the following
in your view write :
<script> var myJsVariable = '#ViewBag.MyVariable' </script>
UPDATE:
A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```
<head>
<script>
var AppConfig = #Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>
And you can use it in your JavaScript code as follow:
<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>
try: var cc = #Html.Raw(Json.Encode(ViewBag.CC)
<script type="text/javascript">
$(document).ready(function() {
showWarning('#ViewBag.Message');
});
</script>
You can use ViewBag.PropertyName in javascript like this.
ViewBag is server side code.
Javascript is client side code.
You can't really connect them.
You can do something like this:
var x = $('#' + '#(ViewBag.CC)').val();
But it will get parsed on the server, so you didn't really connect them.
You can achieve the solution, by doing this:
JavaScript:
var myValue = document.getElementById("#(ViewBag.CC)").value;
or if you want to use jQuery, then:
jQuery
var myValue = $('#' + '#(ViewBag.CC)').val();
None of the existing solutions worked for me. Here's another solution I found that did work:
Controller:
TempData["SuccessMessage"] = "your message here";
View:
let msg = '#TempData["SuccessMessage"]';
Try this:
Anywhere in HTML: <input hidden value=#ViewBag.CC id="CC_id" />
In JS: var CC= document.getElementById("CC_id").value.toString();