I need to declare the 'text value' of the dropdownlist 'dropCallbackReason' into the 'ValueHiddenField' ID of the so that I can then use it as a javascript variable.
I need to be able to declare the HiddenField through C# as aswell as declaring the Javascript Variable 'callBackReason' through c# as well, any ideas how to do this through C#?
.cs page.
protected void Page_Load(object sender, EventArgs e)
{
HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
theForm.Controls.Add(hiddenField);
string script = #"function updateCallBackReason() {
callBackReason = document.getElementById('<%=ValueHiddenField.ClientID %>').value;
return callBackReason;
}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "callBackReasonScript", script, true);
.aspx
<asp:label runat="server" ID="lblCallbackReason" AssociatedControlID="dropCallbackReason" CssClass="textLabel">Reason for callback:</asp:label>
<asp:DropDownList runat="server" ID="dropCallbackReason" onChange="updateCallBackReason" ClientIDMode="Static" >
<asp:ListItem Text="-- Select Reason --" Value="1"></asp:ListItem>
<asp:ListItem Text="Booking a Test Drive" Value="6"></asp:ListItem>
<asp:ListItem Text="Discussing a Purchase" Value="11"></asp:ListItem>
<asp:ListItem Text="Contract Hire Quotation" Value="45"></asp:ListItem>
</asp:DropDownList>
Here is how to add a HiddenField control programmatically. Note that controls cannot be added into Page.Controls directly - they should be placed into some container, like ContentPlaceholder or Panel:
HiddenField hiddenField = new HiddenField {ID = "ValueHiddenField", Value = "test"};
SomePanel.Controls.Add(hiddenField);
And here is how to register a script block:
string script = #"function updateCallBackReason() {
callBackReason = document.getElementById('<%=ValueHiddenField.ClientID %>').value;
return callBackReason;
}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "callBackReasonScript", script, true);
Good places to do this are either Page_Load or Page_PreRender.
Related
I have dropdown inside my asp page and when i am trying to select value then cannt able to get the value in code behind.
Here is my dropdown list code :
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<div class="row" >
<asp:Label ID="LblLanguage" runat="server" Text="Label" meta:resourceKey="LblLanguage">Language</asp:Label>
<asp:DropDownList ID="Language1" runat="server" AutoPostBack="true">
<asp:ListItem Value="auto">Select</asp:ListItem>
<asp:ListItem Value="en-US">English (US)</asp:ListItem>
<asp:ListItem Value="fr">French</asp:ListItem>
</asp:DropDownList>
</div>
</asp:Content>
When i try to select French language from dropdown then code behind no values.Here is my code behind
protected override void InitializeCulture()
{
string lang = Request["Language1"];
if (lang != null && lang != string.Empty)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}
}
So here string lang is having null even i selected a value from dropdown.
You are trying to reference the dropdown Language1 in the old ASP classic way. To obtain the value of your dropdown reference it as Language1.SelectedValue.
string lang = Request["Language1"];
should be
string lang = Language1.SelectedValue;
I have a page with 1 main DropDownList and 2 other. Made it to choose settings for printing report.
The problem is - I use DataSources in these DropDownLists but they haven't an empty value. Where should I put adding a new empty value into DropDownList for correct work?
There is my code (in a comment is a thing that i need to add)
protected void ddlMain_Load(object sender, EventArgs e)
{
switch (ddlMain.SelectedValue)
{
case "1":
dFirst.Visible = true;
dSecond.Visible = false;
break;
case "2":
dFirst.Visible = false;
dSecond.Visible = true;
break;
}
<div>
<asp:DropDownList ID="ddlMain" runat="server" AutoPostBack="true" OnLoad="ddlMain_Load">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2 " Value="2"></asp:ListItem>
</asp:DropDownList>
</div>
<div runat="server" id="dFirst" visible="false">
<asp:DropDownList ID="ddlFirst" runat="server" DataSourceID="sdsFirst"
DataTextField="name" DataValueField="id" OnLoad="ddlFirst_Load">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsFirst" runat="server"
ConnectionString="<%$ ConnectionStrings:conStr %>">
</asp:SqlDataSource>
</div>
//ddlFirst.Items.Add(new ListItem("--Select--", "-1"));
I tried OnLoad secondary element, OnLoad main DropDownList and Page_Load. They don't fit me because new ListItem don't appears when page firstly loading or added more than 1 time when page refreshes.
Use Insert method in page load.
ddlAcademicYear.Items.Insert(0, new ListItem("-- Select --", "-1"));
0 is position at which you want to insert.
Add an optionlabel to your dropdownlist and assign the text "--Select--". Your dropdownlist should now have the desired default value.
UPDATE
I moved the Javascript to the ASPX site instead, and added a postback function for it. Now it works. Thanks to #orgtigger and especially #lucidgold for spending their time helping me!
Here is the update code that works!
<script type="text/javascript">
function changevalue(katoid) {
$('#<%=txtboxchosenkat.ClientID%>').val(katoid);
__doPostBack('<%= updpnlgridview.ClientID %>', '');
}
</script>
Code:
<asp:UpdatePanel ID="updpnlgridview" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtboxchosenkat" style="display:none;" runat="server" OnTextChanged="txtboxchosenkat_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:GridView ID="gridview" runat="server"></asp:GridView>
</ContentTemplate>
</asp:UpdatePane
Code-behind:
protected void hidfldchosenkat_ValueChanged(object sender, EventArgs e)
{
SqlConnection cn2 = new SqlConnection("Server=**,***,***,**;Database=******;
User Id=******;Password=******;");
SqlCommand cmd2 = new SqlCommand("SELECT * FROM tblProducts where KatID='" +
txtboxchosenkat.Text + "'", cn2);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.SelectCommand.CommandText = cmd2.CommandText.ToString();
DataTable dt = new DataTable();
da2.Fill(dt);
gridview.DataSource = dt.DefaultView;
gridview.DataBind();
}
The links (only part of code that makes links):
string line = String.Format("<li><a href='#' onclick='changevalue(" + pid + ");'>{0}",
menuText + "</a>");
Old Post
I need to update a GridView based on the value of a HiddenField. I am currently using a button to populate the GridView, but would like to do it automaticaly as soon as the value in the HiddenField changes.
But when I change the value with a javascript, then event doesn't fire.
(Same thing also happens in case of a TextBox and its OnTextChanged event.)
Not sure if this is way it's meant to work.
A Hidden field will not produce a postback (there is no AutoPostBack property), which means no postback will happen when the value of the hidden field has changed. However, when there is ANY postback from the page then OnValueChangd event will execute if a hidden field value has changed.
So you should try the following ideas:
1) Update your JavaScript for changevalue as follows:
function changevalue(katoid)
{
document.getElementById('" + hidfldchosenkat.ClientID + "').value=katoid;
_doPostBack(); // this will force a PostBack which will trigger ServerSide OnValueChange
}
2) Change your HiddenField to a TextBox but set the Style="display:none;" and set AutoPostBack="true":
<asp:TextBox runat="server" ID="hidfldchosenkat"
Value="" Style="display:none;"
AutoPostBack="true" OnTextChanged="hidfldchosenkat_TextChanged">
</asp:TextBox>
This example works great for me:
JavaScript:
function changevalue()
{
$('#<%=hidfldchosenkat.ClientID%>').val("hi");
}
ASPX Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="hidfldchosenkat" runat="server" AutoPostBack="true"
ontextchanged="hidfldchosenkat_TextChanged"></asp:TextBox>
<asp:Button ID="Button1"
runat="server" Text="Button" OnClientClick="changevalue()" />
</ContentTemplate>
</asp:UpdatePanel>
C# Code-Behind:
protected void hidfldchosenkat_TextChanged(object sender, EventArgs e)
{
string x = "hi"; // this fires when I put a debug-point here.
}
Your issue could be with:
document.getElementById('" + hidfldchosenkat.ClientID + "').value=katoid
You may want to try:
$('#<%=hidfldchosenkat.ClientID%>').val(katoid);
Also you should PUT changevalue() inside your ASPX JavaScript tags and not register it for every LinkButton.... so instead try the following:
protected void lagerstyringgridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Assuming the LinkButtons are on the FIRST column:
LinkButton lb = (LinkButton)e.Row.Cells[0].Controls[0];
if (lb != null)
lb.Attributes.Add("onClick", "javascript:return changevalue(this);");
}
}
You can have any event fire by doing a __doPostBack call with JavaScript. Here is an example of how I used this to allow me to send a hiddenfield value server side:
ASPX
<asp:HiddenField runat="server" ID="hfStartDate" ClientIDMode="Static" OnValueChanged="Date_ValueChanged" />
JavaScript
$('#hfStartDate').val('send this');
__doPostBack('hfStartDate');
This will call the OnValueChanged event and cause a postback. You can also set this is a trigger for an update panel if you would like to do a partial postback.
Using C# I need the value in the Hiddenfield below, which is currently "test" to be the 'Text' of the DropDownList. Any Ideas?
HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
.cs page.
protected void Page_Load(object sender, EventArgs e)
{
HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
theForm.Controls.Add(hiddenField);
string script = #"function updateCallBackReason() {
callBackReason = document.getElementById('<%=ValueHiddenField.ClientID %>').value;
return callBackReason;
}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "callBackReasonScript", script, true);
.aspx
<asp:label runat="server" ID="lblCallbackReason" AssociatedControlID="dropCallbackReason" CssClass="textLabel">Reason for callback:</asp:label>
<asp:DropDownList runat="server" ID="dropCallbackReason" onChange="updateCallBackReason" ClientIDMode="Static" >
<asp:ListItem Text="-- Select Reason --" Value="1"></asp:ListItem>
<asp:ListItem Text="Booking a Test Drive" Value="6"></asp:ListItem>
<asp:ListItem Text="Discussing a Purchase" Value="11"></asp:ListItem>
<asp:ListItem Text="Contract Hire Quotation" Value="45"></asp:ListItem>
</asp:DropDownList>
After binding your drop down to a data source, set the selected value of the drop down to the index of the text in the hidden field.
dropCallbackReason.SelectedIndex = dropCallbackReason.Items.IndexOf(dropCallbackReason.Items.FindByText(ValueHiddenField.Value.ToString()));
I'd say your function updateCallBackReason is not doing what is supposed to do (update hidden field value). If didn't get wrong your question, this is what you have to do.
string script = string.Format(#"function updateCallBackReason() {{
var ddl = document.getElementById('dropCallbackReason');
var callBackReason = document.getElementById('{0}');
callBackReason.value = ddl.options[ddl.selectedIndex].innerHTML;
}}", hiddenField.ClientID );
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();