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.
Related
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;
Hi i have facebook login code i want to use javascript varibles values on code behind.I can use by saving them in hidden field but there is no button click so page is not postback.
here is my code:
<script>
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: '550050651719081', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
FB.api('/me', function (me) {
**document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('Email').innerHTML = me.email;
document.getElementById('profileImg').src = uid;**
})
}
});
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login with Facebook</div>
</div>
<div id="auth-loggedin" style="display: none">
Name: <b><span id="auth-displayname"></span></b>(logout)<br />
Email: <b><span id="Email"></span></b><br />
Profile Image: <img id="profileImg" />
</div>
</div>
code is working properly but i want to get name,email and uid on code behind also.
You have send it one way or another to the server:
Either
1) directly via AJAX and catch it on the other side with an MVC-Controller
2) indirectly e.g via Server Controls and PostBack.
You could use a hiddenfield server control to hold values that will be accessible on postback if using WebForms.
If using MVC, you can add properties to a view model and use the Html.HiddenFor helper, which will be accessible by JavaScript.
You could use ajax though, start here. This will allow you to essentially do it behind the scenes to the user and allow transform during and after the response is fetched. Of course, you would have to write the server side code to catch and process this request.
I want to set the Image URL of Image control using client side code and save the image to the server using C# code. Here is what i have implemented:
<asp:Button ID="btnImageUpload" OnClick="btnImageUpload_Click" runat="server" Text="Preview" CausesValidation="false" OnClientClick="Image_View();"/>
C# Code:
protected void btnImageUpload_Click(object sender, EventArgs e)
{
if (Directory.Exists(#"C:\\Images"))
SaveImage_Server();
else
{
Directory.CreateDirectory(#"C:\\Images");
SaveImage_Server();
}
}
public void SaveImage_Server()
{
try
{
if (FlUpldImage.PostedFile.ContentLength > 0)
{
String fn = Convert.ToString(DateTime.Now) + Path.GetFileName(FlUpldImage.FileName);
if (fn.Contains('/'))
{
fn = fn.Replace("/", "");
}
if (fn.Contains(':'))
{
fn = fn.Replace(":", "");
}
if (fn.Contains(" "))
{
fn = fn.Replace(" ", "");
}
String Saved_ImagePath = #"C://Images/" + fn; // making the path with created dynamically folder name
FlUpldImage.SaveAs(Saved_ImagePath);
HidnLocalImageURL.Value = Saved_ImagePath;
}
}
catch (Exception re)
{
}
}
JavaScript
function Image_View() {
// __doPostBack('<%= btnImageUpload.ClientID %>', '');
// var clickButton = document.getElementById("<%= btnImageUpload.ClientID %>");
// clickButton.click()
var idFlUpload = '<%= FlUpldImage.ClientID %>';
var fu1 = document.getElementById(idFlUpload);
var idImgCntrl = '<%= imgCorrect.ClientID %>';
var ImgCntrl = document.getElementById(idImgCntrl);
alert("You selected " + fu1.value);
ImgCntrl.setAttribute('src', fu1.value);
}
Now my issue is that once the server side code is executed the page gets refreshed and the link set to Image control using JS gets reset to default value.
How can i get this working wherein the image also gets saved and Image URL property also gets set through JS.
If there is any other way to implement this than please let me know. Thanks in Advance!
You have to set it on server too. You can use hidden field to save the url and access that hidden field on server to get the url to set mgCntrl.ImageUrl
In html
<input type="hidden" runat="server" id="hdnImageSrc" />
On Client javascript
hdnImageSrc = document.getElementById('<%= hdnImageSrc.ClientID %>');
mgCntrl.setAttribute('src', fu1.value);
hdnImageSrc.value = fu1.value;
On server side code
mgCntrl.ImageUrl = hdnImageSrc.Value;
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.
I have an ASP.NET ImageButton that OnClientClick() is supposed to fire a js function that reads the values from a two text fields, send it to a server-side WebMethod. With the WebMethod sending it to another entity method which handles the storage. I've tried debugging by setting breakpoints in the WebMethod and storage method on the serverside but neither is getting reached. I then tried setting a breakpoint on client-side using the Mozilla Firebug tool. The js function never gets called and the page just refreshes. I set a breakpoint in another js function and it was traced perfectly. Any help?
ASP
<asp:ImageButton input="image" ID="btnSend" ImageUrl="Images/send_button.jpg"
runat="server"
onclientclick="javascript:handle(); return false">
</asp:ImageButton>
JS
function handle() {
window.$get("#" + "<%= btnSend.ClientID %>").click(
function () {
var txtVC = window.$get("#" + "<%= txtVC.ClientID %>").value();
var txtMsg = window.$get("#" + "<%= tbMgSend.ClientID %>").value();
if (txtVC != "" || txtMsg != "") {
window.PageMethods.SendMsg(txtVC, txtMsg, txtMessageResult);
return window.$get("#" + "<%= lblMessageStatus.ClientID%>").value("SUCCESS"),
alert("SUCCESS");
}
else {
return alert("Text Message is Empty!");
}
});
}
function txtMsgResult(result) {
if (result != '') {
window.$("#" + "<%= lblMessageStatus.ClientID %>").innerHTML = result;
alert("SUCCESS");
}
}
I've tried the following:
* OnclientClick with and without return
* $get with and without concat(+)
* changing the server-side to a method instead of web method and that also didn't fire
Have you tried it without the return false?
<asp:ImageButton input="image" ID="btnSend" ImageUrl="Images/send_button.jpg"
runat="server"
onclientclick="handle()">
</asp:ImageButton>
Maybe it doesn't work because it autoPostBack.
I'm not sure there is a way to turn it off in an ImageButton. Why not use a HTML control instead ?