I have this function on aspx(html)
<body onload="NewPage2()">
<script type="text/javascript">
function NewPage2() {
var url = getUrlVars(url);
document.getElementById("HiddenField1").Value = url["access_token"];
}
</script>
<div class = content>
<form id="form1" runat="server">
<asp:HiddenField id="HiddenField1" runat="server" Value=""/>
</form>
CODE1: <asp:Label ID="Label1" runat="server" Text="Label" ForeColor="#CC0000" />
</div>
</div>
</body>
how can I get the var(on jquery(html)) to my variableURL2 in aspx.cs?
protected void Page_Load(object sender, EventArgs e)
{
string code = HiddenField1.Value;
Label1.Text = code;
saveToken(token, code);
}
Have one server hidden control in .aspx page
<asp:HiddenField Id="HiddenField1" runat="server"></asp:HiddenField>
in browser it will be rendered like this
<input type="hidden" id="HiddenField1" />
assign values from javascript
document.getElementById("HiddenField1").value = "your values here";
in aspx.cs render like this
string variableURL2 = HiddenField1.Value;
There are two ways you can do this, and both would have to be from a post back since the javascript is fired after the page loads.
redirect and append to the query string, then read it from c#
javascript:
location.href = "/mypage.aspx?variable2=VARFROMJAVASCRIPT";
c#
string variable2 = Request.QueryString["variable2"];
or set the value to a hidden field like above
javascript:
var $hiddenInput = $('',{type:'hidden',id:'variable2',value:'VARFROMJAVASCRIPT'});
$hiddenInput.appendTo('body');
c#
string variable2 = Request["variable2"];
.aspx:
<asp:HiddenField id="HiddenField1" runat="server" value=""/>
javascript:
function end(url) {
var url = getUrlVars(url);
var url2 = url["access_token"];
document..getElementById("HiddenField1").value = url2;
}
.cs file:
string variableURL2 = HiddenField1.Value;
Use server control HiddenField
First you have to add control in your aspx/ascx/master file
<asp:HiddenFiled ID="hdn" runat="server"/>
Then you can use this control in JS
function end(url) {
var url = getUrlVars(url);
var url2 = url["access_token"];
<%= hdn.ClientId %>.value = url["access_token"];
}
in code behind
protected void Page_Load(object sender, EventArgs e)
{
string variableURL2 = hdn.Value;
}
Related
I am trying to deserialize JSON to C# list. I have the Jquery code as,
$(document).ready(function () {
$("#btn_check").click(function () {
var str="";
x = $("#frm").serializeArray();
$("#Label1").empty();
$.each(x, function (i, field) {
// $("#Label1").append(field.name + ":" + field.value + " ");
str = str + field.name + ":" + field.value + " ";
});
var jsonstr=JSON.stringify(str); });
});
after stringify, I get something weird as jsonstr=
__VIEWSTATE:/wEPDwUKLTg1MjI5MDU0MWQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFjIFB2NoZWNrXzAFB2NoZWNrXzEFB2NoZWNrXzIFB2NoZWNrXzMFB2NoZWNrXzQFB2NoZWNrXzUFB2NoZWNrXzYFB2NoZWNrXzcFB2NoZWNrXzgFB2NoZWNrXzkFCGNoZWNrXzEwBQhjaGVja18xMQUIY2hlY2tfMTIFCGNoZWNrXzEzBQhjaGVja18xNAUIY2hlY2tfMTUFCGNoZWNrXzE2BQhjaGVja18xNwUIY2hlY2tfMTgFCGNoZWNrXzE5BQhjaGVja18yMAUIY2hlY2tfMjEFCGNoZWNrXzIyBQhjaGVja18yMwUIY2hlY2tfMjQFCGNoZWNrXzI1BQhjaGVja18yNgUIY2hlY2tfMjcFCGNoZWNrXzI4BQhjaGVja18yOQUIY2hlY2tfMzAFCGNoZWNrXzMxBQhjaGVja18zMgUIY2hlY2tfMzMFCGNoZWNrXzM0BQhjaGVja18zNQUIY2hlY2tfMzYFCGNoZWNrXzM3BQhjaGVja18zOAUIY2hlY2tfMzkFCGNoZWNrXzQwBQhjaGVja180MQUIY2hlY2tfNDIFCGNoZWNrXzQzBQhjaGVja180NAUIY2hlY2tfNDUFCGNoZWNrXzQ2BQhjaGVja180NwUIY2hlY2tfNDgFCGNoZWNrXzQ5s98N0sYArkR3uk7Sb4bJWOocOpU= __VIEWSTATEGENERATOR:172284EE __EVENTVALIDATION:/wEWNAKauo6nDAK5rJ0YAp7D/4IGAoPa4e0LAujww9gBAs2HpsMHArKeiK4NApe16pgDAvzLzIMJApH2i8IBAvaM7qwHAp7Dv7UBAp7Dq9oIAp7Dl/8PAp7Dg6QHAp7Dj6IEAp7D+8YLAp7D5+sCAp7D05AKAp7Dn9wLAp7Di4EDAoPaoaAHAoPajcUOAoPa+ekFAoPa5Y4NAoPa8YwKAoPa3bEBAoPaydYIAoPatfsPAoPagccBAoPa7esIAujwg4sNAujw768EAujw29QLAujwx/kCAujw0/cPAujwv5wHAujwq8EOAujwl+YFAujw47EHAujwz9YOAs2H5vUCAs2H0poKAs2Hvr8BAs2HquQIAs2HtuIFAs2HoocNAs2HjqwEAs2H+tALAs2HxpwNAs2HssEEAvCFnqIPppJbhAvF8AzSoMd/uZfiRXpzWu0= check_0:on check_1:on check_2:on check_3:on check_4:on check_5:on check_6:on check_7:on check_8:on check_9:on check_10:on check_11:on check_12:on check_13:on check_14:on check_15:on check_16:on check_17:on check_18:on check_19:on check_20:on check_21:on check_22:on check_23:on check_24:on check_25:on check_26:on check_27:on check_28:on check_29:on check_30:on check_31:on check_32:on check_33:on check_34:on check_35:on check_36:on check_37:on check_38:on check_39:on check_40:on check_41:on check_42:on check_43:on check_44:on check_45:on check_46:on check_47:on check_48:on check_49:on
check_0 to check_1 are the dynamically created checkboxes and I want to get their values in C# as list or in any form to interpret and push them into Database.
asp.net:
<form id="frm" runat="server">
<asp:Panel ID="pnl_seat" runat="server">
<asp:PlaceHolder ID="plhdr_seat" runat="server">
checkboxes are dynamically created here
</asp:PlaceHolder>
<br />
<button id="btn_check" type="button">Serialize form values</button>
<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="btn_submit_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
</asp:Panel>
</form>
picture:
C# code:
using Newtonsoft.Json;
class abc // some class
{
protected void btn_submit_Click(object sender, EventArgs e)
{
List<Test> myDeserializedObjList = (List<Test>) Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonstr"], typeof(List<Test>));
}
}
the above code I got it from codeproject.com.
But on running this code, I am getting an exception that "str" as "null". How to push the label1 or str to server side? Help me please.
Could you paste more code? It's hard to find any issues from the limited source code.
You may send the str to server using an ajax request:
$.get('your url', {str: str})
By the way, It seems the str is not a valid JSON string. str = JSON.strigify(x) will stringify the object to a JSON string.
Try this:
```
$(document).ready(function () {
$("#btn_check").click(function () {
var x = $("#frm").serializeArray();
$("#Label1").empty().text(JSON.stringify(x));
});
});
using Newtonsoft.Json;
class abc // some class
{
protected void btn_submit_Click(object sender, EventArgs e)
{
List<Test> myDeserializedObjList = (List<Test>) Newtonsoft.Json.JsonConvert.DeserializeObject(Label1.Text, typeof(List<Test>));
}
}
```
JQUERY:
$(document).ready(function () {
$("#btn_check").click(function () {
var str = "";
x = $("#frm").serializeArray();
str = JSON.stringify(x);
// $("#HiddenField1").Value(str);
$('#<%=hdnSelectedTicket.ClientID %>').val(str);
<%-- $('#<%=hdnSelectedTicket.ClientID %>')--%>
});
});
ASP.NET:
<form id="frm" runat="server">
<asp:HiddenField ID="hdnSelectedTicket" runat="server" />
<asp:Panel ID="pnl_seat" runat="server">
<asp:PlaceHolder ID="plhdr_seat" runat="server"></asp:PlaceHolder>
<br />
<button id="btn_check" type="button">Serialize form values</button>
<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="btn_submit_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
</asp:Panel>
</form>
C#:
using Newtonsoft.Json;
protected void btn_submit_Click(object sender, EventArgs e)
{
//string a = hdnSelectedTicket.Value;
List<Test> myDeserializedObjList = (List<Test>)Newtonsoft.Json.JsonConvert.DeserializeObject (hdnSelectedTicket.Value, typeof(List<Test>));
}
I am posting this question again, maybe this time more accurate description.
The problem is , I am using jQuery to set the Label's text value and it works fine on browser, but when I want to save it to string, it does not save it. Here is the
front End Html Code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
And here is the Back End C# Code On Page Load
using System;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
The result displayed is
Name's not Fine
Ronaldo
Seems like the string is still Null. Is there any problem of rendering??
label is not input type so you can not get changed values through jquery on server side. You can use hidden field for this purpose.
Your server side code (c#) can not access the form data until your client side code (HTML/Javascript) posts it.
Why do you want to the name already at the PageLoad event?
You could add a asp:Button with an attached onClick event handler to read the value of your asp:Label.
Labels do not maintain viewstate. The server will not post that information back to the server. You can try explicitly enabling the ViewState on your Label, but if that doesn't work, you will have to store that value in a hidden field.
First Call Page Load event and after that call JQuery Window.Load event.
So if you want to set any content in Label then you can do using onClientClick of button.
For ex.
<asp:Button ID="btn" runat="server" Text="Click me" OnClientClick="SetClientValues();" />
<script type="text/javascript">
function SetClientValues() {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
}
</script>
At server side button event you can get Label values that sets at client side.
protected void btn_Click(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
It will print Yes Name is Fine
This should do it:
<script type="text/javascript">
$(window).load(function () {
if($('#<%= Txt1.ClientID %>').val() != "Ronaldo"){
var myNewName = "Ronaldo";
$('#<%= Txt1.ClientID %>').val(myNewName);
$('#<%= Label1.ClientID %>').text(myNewName);
$('#<%= Btn1.ClientID %>').click();
}
});
</script>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="Txt1" runat="server" style="display:none"></asp:Label>
<asp:Button ID="Btn1" runat="server" style="display:none" Click="Btn1_Click"></asp:Label>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Label1.Text=Txt1.Text;
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
protected void Btn1_Click(object sender, EventArgs e)
{ }
Hope it helps :)
I have the following code in the Page_Load method of a web form:
protected void Page_Load(object sender, EventArgs e)
{
CountrySelectButton.Click += new EventHandler(CountrySelectButton_Click);
if (HomePage.EnableCountrySelector) //always true in in this case
{
if(!IsPostBack)
BindCountrySelectorList();
}
}
The BindCountrySelectorList method looks like this:
private void BindCountrySelectorList()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(HomePage.CountryList);
var ds = nvc.AllKeys.Select(k => new { Text = k, Value = nvc[k] });
CountrySelector.DataSource = ds;
CountrySelector.DataTextField = "Text";
CountrySelector.DataValueField = "Value";
CountrySelector.DataBind();
}
And I have a LinkButton click event handler which gets the SelectedValue from the SelectList as so:
void CountrySelectButton_Click(object sender, EventArgs e)
{
//get selected
string selectedMarket = CountrySelector.SelectedValue; //this is always the first item...
//set cookie
if (RememberSelection.Checked)
Response.Cookies.Add(new HttpCookie("blah_cookie", selectedMarket) { Expires = DateTime.MaxValue });
//redirect
Response.Redirect(selectedMarket, false);
}
EDIT:
This is the DDL and LinkButton definition:
<asp:DropDownList runat="server" ID="CountrySelector" />
<asp:LinkButton runat="server" ID="CountrySelectButton" Text="Go" />
Resulting markup:
<select name="CountrySelector" id="CountrySelector">
<option value="http://google.com">UK</option>
<option value="http://microsoft.com">US</option>
<option value="http://apple.com">FR</option>
</select>
<a id="CountrySelectButton" href="javascript:__doPostBack('CountrySelectButton','')">Go</a>
END EDIT
ViewState is enabled but the SelectedValue property only ever returns the first item in the list regardless of which item is actually selected. I'm certain I'm missing something obvious but I can't find the problem; any help is much appreciated.
Thanks in advance.
Dave
You are correct that your issue stems from the jquery ui dialog... you can get around this by using a hidden field to record the value of the dropdownlist. Then in your code, reference the hidden field.
Front end could look like:
<div id="myModal" style="display: none;">
<asp:DropDownList runat="server" ID="SelectList" />
<asp:LinkButton runat="server" ID="MyButton" Text="Go" />
</div>
<input type="hidden" id="countryVal" runat="server" />
<a id="choose" href="#">Choose</a>
<script type="text/javascript">
$(document).ready(function () {
$('#choose').click(function () {
$('#myModal').dialog({
});
return false;
});
$('#<%= SelectList.ClientID %>').change(function () {
var country = $(this).val();
$('#<%= countryVal.ClientID %>').val(country);
});
});
</script>
Then your code behind:
var selected = countryVal.Value;
Wrap the MyButton.Click+=... statement inside (!IsPostBack) like
if(!IsPostBack)
{
MyButton.Click += new EventHandler(MyButton_Click);
BindSelectList();
}
I have two labels:
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
and I set innerHTML by javascript:
document.getElementById('Label1').innerHTML = position.lat();
document.getElementById('Label2').innerHTML = position.lng();
How I can get those labels values in codebehind? I try:
TextBox2.Text = Label1.Text;
UPDATE:I need to get pushpin location:
<artem:GoogleMap ID="GoogleMap1" runat="server"
EnableMapTypeControl="False" MapType="Roadmap" >
</artem:GoogleMap>
<artem:GoogleMarkers ID="GoogleMarkers1" runat="server"
TargetControlID="GoogleMap1" onclientpositionchanged="handlePositionChanged">
</artem:GoogleMarkers>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<script type="text/javascript">
var list = document.getElementById("Label1");
function handlePositionChanged(sender, e) {
printEvent("Position Changed", sender, e);
}
function printEvent(name, sender, e) {
var position = e.latLng || sender.markers[e.index].getPosition();
document.getElementById('Label1').innerHTML = position.lat();
document.getElementById('Label2').innerHTML = position.lng();
}
</script>
protected void Button1_Click(object sender, EventArgs e)
{
TextBox2.Text = Label1.Text;// return value: Label
}
You cannot access the value on server side. You will have to use a hidden field for that:
<asp:HiddenField ID="Hidden1" runat="server" />
The set the innerHtml value in the Hidden field by doing:
document.getElementById('<%= Hidden1.ClientID %>').value = position.lat();
You can then access it from server side by doing:
TextBox1.Text = Hidden1.Value;
You are not able to do that with the Label control as when the page is posted back the content of labels are not posted to the server. You would need to make use of an input control of sorts. Probably a hidden input would be your best bet.
Take a hidden field like below
<asp:HiddenField ID="hdnBody" ClientIDMode="Static" runat="server" />
Then set its value in Jquery like below
<script>
function GetEmailID() {
var bodyHtml = $("#editor").html();
$("#hdnBody").val(bodyHtml);
}
</script>
And in the code behind do this to get it
string body = hdnBody.Value;
I have been searching through here and google for a few days now, trying to figure out why I cannot get the value of a hiddenfield variable in javascript. When accessed, the value is returned as undefined.
I have an ASP HiddenField inside an UpdatePanel which is part of a custom user control in a .aspx web page (standard issue).
In my user control, I need to get the .Value of the HiddenField (hdnServer) in javascript after setting it in C#. But for some reason the following is not getting the correct value.
The MessageBox in the C# code returns the correct value (the code here has test values), but when accessed in javascript is undefined.
userControl.ascx:
//this function is called when the timer created in document.ready() elapses
//returns the correct hdnServer value in the check.
var checkHdn = function () {
var temp = document.getElementById("<%=hdnServer.ClientID%>").value;
temp = temp.toString();
if (temp != "") {
$('#LoadingViewer').hide();
clearInterval(checkSrv);
//enable start button
$('#startBtn').attr("Enabled", "true");
}
};
function RdpConnect() {
//serverName = undefined here. should be ip address when set in c#
var serverName = document.getElementById("<%= hdnServer.ClientID %>").value;
alert(serverName);
if (serverName != "") {
MsRdpClient.Server = serverName;
}
};
userControl.ascx.cs code-behind:
public partial class userControl : System.Web.UI.UserControl
{
System.Timers.Timer timer;
protected void Page_Load(object sender, EventArgs e)
{
timer = new System.Timers.Timer(5000);
timer.Start();
}
protected void testOnTick(object sender, System.Timers.ElapsedEventArgs e)
{
hdnServer.Value = "test value";
startBtn.Enabled = true;
timer.Enabled = false;
}
}
Here is the asp for HiddenField just in case: userControl.ascx:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>
<!--trigger not used -->
<!-- <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />-->
</Triggers>
<ContentTemplate>
<asp:HiddenField ID="hdnServer" runat="server" />
<asp:Label ID="Label1" Text="Loading, please wait." CssClass="loading" runat="server"
Font-Size="XX-Large" />
</ContentTemplate>
</asp:UpdatePanel>
Thank you for any advice in advance!
EDIT: messagebox removed..
Here is rendered html: http://pastie.org/3122247
You need to set ClientIDMode if you want to make it simple:
<asp:HiddenField runat="server" ClientIDMode="Static" Id="hidServer"/>
<script type="text/javascript">
alert($("#hidServer").val());
</script>
Or, use the ClientID property if you don't set ClientIDMode:
<asp:HiddenField runat="server" Id="hidServer"/>
<script type="text/javascript">
alert($("<%= hidServer.ClientID %>").val());
</script>
User controls have always been a strange issue for referencing using js and then master pages to go along with it.
For the hidden field do this:
<asp:HiddenField ID="hdnServer" runat="server" ClientIDMode="Static" />
in the js, do this:
var serverName = document.getElementById('hdnServer').value;
Try this:
var temp = $('#mytestcontrol_hdnServer').val();
you need to use ' not "
like:
var serverName = document.getElementById('<%= hdnServer.ClientID %>').value;
be careful don't use ". You have only use '
You can do this:
var temp = $('#hdnServer').val();
Instead of :
var temp = document.getElementById("<%=hdnServer.ClientID%>").value;
Also change this:
var serverName = document.getElementById("<%= hdnServer.ClientID %>").value;
To this:
var serverName = $('#hdnServer').val();