ASP.NET hidden field not updating after postback - javascript

I have some code on my ASP page which looks like this:
<asp:UpdatePanel runat="server" id="updatepanel1" UpdateMode="Conditional" onload="updatepanel1_Load" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:HiddenField id="sendingRequest" runat="server" Value="0" />
....
</ContentTemplate>
</asp:UpdatePanel>
I also have some javascript on my page which does this, to trigger the update of the updatepanel:
var sendingRequest = document.getElementById("<%=sendingRequest.ClientID%>");
sendingRequest.value = "1";
__doPostBack('<%= updatepanel1.ClientID %>', '');
Everything works fine up to now, but in my updatepanel1_Load event, I try to set the value back to "0" :
sendingRequest.Value = "0";
This value never gets updated and set back to 0 on the client after the postback, and I can't figure out why!
Can anyone help? Thanks

If you're having problems with a hidden field, you could use a TextBox instead. Hide the textbox with css (display: none;) to achieve similar results to a hidden field. Its not exactly pretty, but its a workable workaround.

Try to call registerstartupscript or something like that from server side. I can't remember exactly the method name but its part of page object. This will register any javascript you would like to execute after postback on the client side.

This similar scenario is done here successfully:
http://encosia.com/easily-refresh-an-updatepanel-using-javascript/
Ensure you are following the same steps - I can't see all of your code. Try with a label first to make sure it gets updated as a visible control. If that works then narrow it down with your hidden value to make sure the behavior isn't different for a hidden control.

I had an issue with three HiddenFields being set in Code-Behind, but their values were not set when polled from JQuery.
My issue turned out being that my Master Page uses an UpdatePanel, and in my ASP.Net Init event I was purposing that UpdatePanel with conditional rendering.
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
mstr = CType(Master, Site)
'setup partial rendering so Log can update asynchronously
scriptManager = CType(mstr.FindControl("ScriptManager1"), ScriptManager)
scriptManager.EnablePartialRendering = True
scriptManager.AsyncPostBackTimeout = 28800
CType(mstr.FindControl("UpdatePanel1"), UpdatePanel).UpdateMode = UpdatePanelUpdateMode.Conditional
CType(mstr.FindControl("UpdatePanel1"), UpdatePanel).ChildrenAsTriggers = False
End Sub
The issue was that I forgot to then call update on my panel after setting the HiddenFields. I had to do this because my button was a partial-postback control (UseSubmitBehaviour=False)
hfParams.Value = paramlist.ToString()
hfForms.Value = formlist.ToString()
hfStartJob.Value = "True"
CType(mstr.FindControl("UpdatePanel1"), UpdatePanel).Update()

Related

Check if ASP Label is visible on different page?

The current code I am working on is a mess. Currently, I have an aspx page that has some javascript and sets a tooltip for various asp:buttons that are on an ascx page (not the current aspx). It looks like this:
function setTooltips() {
$("[id*='btnSave']").mousemove(function (ev) { ButtonToolTip(ev, this, "Click to save"); });
$("[id*='btnClear']").mousemove(function (ev) { ButtonToolTip(ev, this, "Clear fields"); });
// more button tooltips set.
}
In the ascx page, I also have an asp:label. I'm creating a javascript method to display an alert based on the visibility of this label. I'm having trouble finding the control and its visibility.
Here is what the asp label code looks like:
<asp:UpdatePanel runat="server" ID="upnl_alert" UpdateMode="Always">
<ContentTemplate>
<asp:Label ID="lbl_alert" runat="server" Text="There are several issues found.<br /><br />" Visible="false" />
</ContentTemplate>
</asp:UpdatePanel>
Is there a way to check the visibility of the asp label so that I can implement the function I just wrote for the alert?
I have tried:
if (document.getElementById('lbl_alert').style.visibility == "visible")
but I am getting DOM exception - failed to execute.
Thanks in advance for the help.
have an aspx page that has some javascript and sets a tooltip for various asp:buttons that are on an ascx page (not the current aspx).
Well, not quite!!! Context here matters.
Any "user" control built and dropped into any page?
the markup, the controls, and javascript and whatever else that ascx control has? It is placed in your existing aspx page. So, no, the controls are NOT in some other page.
better to state you have a user control dropped into a existing page, and, thus I want to select/use/enjoy/hide/show or do whatever with some of the buttons that the user control has.
Like all pages, most controls will often receive the current page class, or namespace as a prefix. And keep in mind, what happens if you drag that user control 2 or 4 times into the existing page? Then what do the buttons "id" become? I mean, the buttons can't have the same id, and yet it's perfect legal to drop in the user control multiple times, and each time, it will pull into the current page that markup.
So, say a super simple user control (ascx) is like this:
code behind for this UC (button click)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs)
Me.Label1.Text =
$"control id = {Me.ClientID} <br/>
Button ID = {Button1.ClientID} <br/>
LableID = {Label1.ClientID}"
End Sub
Ok, so now lets create a new blank page, and drag + drop in the above.
We now have this:
<uc1:UserButton runat="server" id="UserButton" />
<br />
<br />
<uc1:UserButton runat="server" id="UserButton1" />
<br />
<asp:Button ID="Button1" runat="server" Text="JavaScript - get Label 1"
OnClientClick="gettest();return false"
/>
<script>
function gettest() {
// var sLbl = '<%=UserButton.ClientID + "_Label1" %>'
var sLbl = 'UserButton_Label1'
var lbl1 = document.getElementById(sLbl)
sResult = "Value of label1 in control is \n" + lbl1.innerText
alert(sResult)
}
</script>
So, since I dropped in the UC two times?
then how do the lables, and buttons get seperated out?
Simple:
The controls "inside" each control are prefixed with the "id" you give the user control, and THEN a "_" and THEN the control inside.
So, note close the js code I used:
// var sLbl = '<%=UserButton.ClientID + "_Label1" %>'
var sLbl = 'UserButton_Label1'
var lbl1 = document.getElementById(sLbl)
sResult = "Value of label1 in control is \n" + lbl1.innerText
alert(sResult)
So, when I run the above, I thus get this:
So you need to prefix the control you want inside of the ascx page with the "id" of the control name used in the CURRENT page!
That's why I stated context matters here. the ASCX page does NOT matter, what matters is the name of the "UC" control used on the current page, since WHEN such controls are dragged + dropped into a existing page, then the controls for that UC control are prefixed with the "id" of the user control.
So, to be clear:
The controls are NOT in the other page, and that's really only a consdieration and view during design time.
At run time, those ascx controls are pulled + injected + rendered in the CURRENT page. Hence you can/have to prefix the controls in that ascx page with the "id" of the UC control used when "dropping" that control into any web page you like.
User controls are fantastic, since they represent re-usable controls, but at the end of the day, such controls are rendered in the current page.

How do I update ASP Dropdown whose list item are added by jQuery AJAX call : Error Invalid postback or callback

I have a simple problem which I complicated. My web application has a ASP Dropdown whose values I wish to populate from the database. So I use jquery and Ajax to perform and dynamically add the list item to the dropdown which I am successful at. However as soon as I select a value and hit the submit button I get the
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
I realize the problem is that since server side is not aware of these newly added values it throws this error. I absolutely need the ASP dropdown and cannot use Select hence the only option I have is to use update Panel which I am completely unfamiliar with. I gave it a shot but it didn't work and since last 3 hours I am stuck and cant move forward.
My AJAX Call looks like
$.ajax({
type: "POST",
url: "salesQuote.aspx/getLabelAndValue",
data: "{fieldName: \"tier\"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("karan");
$.each(msg.d, function () {
$("#tier").append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("Failed to load names");
}
});
The c# web service looks like
[WebMethod]
public static ArrayList getLabelAndValue(string fieldName)
{
try
{
//.....database connection...
ArrayList temp = new ArrayList();
while (dr.Read())
{
temp.Add(new ListItem( (string)dr.GetValue(0), (string)dr.GetValue(1)) );
}
return temp;
....
}
The ASP dropdown with update panel looks like
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:DropDownList class="form-control" ID="tier" runat="server" AutoPostBack="true" OnSelectedIndexChanged="tierAccessChange" >
</asp:DropDownList>
</ContentTemplate>
<triggers>
<asp:asyncpostbacktrigger controlid="tier" eventname="SelectedIndexChanged" />
</triggers>
</asp:UpdatePanel>
I don't know what to do next or what I have done is right. Please point me to the correct direction as to how do I get the selected value after hitting the submit button in the control of dropdown.
Edit 1: I tried adding in the web config. I got rid of the error but I couldnt get the selected value in the control after submitting
<system.web>
<pages enableEventValidation="false"/>
</system.web>
Webforms have a tendency to make you do things their way. Instead of adding the option to the control on the client you could try posting the new value to the server and then adding the option to the dropdown in your server code. (Even if you add it from the client you'll probably want to add the new value server-side after you receive it. Otherwise it won't be persisted as an item in the list. It will just disappear.)
Also, how are you reading the value of the dropdown? ASP.NET might not recognize it as an option in the server control, but it's still getting posted when the form is submitted. You could read it directly from Request.Form["YourDropDownClientId"].

Change labels text with javascript and read it from code behind

I have an asp.net page with a label on it. The label has no text.
<asp:Label ID="Label1" runat="server"></asp:Label>
At some point, I call a javascript function that adds some content to the label, as follows:
function myFunc() {
label = document.getElementById("Label1");
list = document.getElementById("list");
label.innerHTML = list.innerText;
}
After that function is done, I click a button on the page, that calls its onclick event:
protected void Button1_Click(object sender, EventArgs e)
{
string a = Label1.Text;
}
For some reason, the Label1.Text is still empty. Why? Is there any way I could fix this?
Thanks.
Because the value doesn't get posted to the code-behind.
No matter how much WebForms tries to hide this, the only data that gets posted from a web page to the server is data that's in form elements. What WebForms does with things like label texts is stuff them into an input type="hidden" as one big serialized base-64 encoded string. (It calls this "view state" but it's really just a hidden form element.)
Changing the page markup doesn't change anything server-side because page markup isn't posted to the server.
What you can do is create a form element and change that along with the markup. Something as simple as:
<asp:HiddenField runat="server" ID="Hidden1" />
Whenever you change the markup in JavaScript, also change that value:
label = document.getElementById("Label1");
hidden = document.getElementById("Hidden1");
list = document.getElementById("list");
label.innerHTML = list.innerText;
hidden.value = list.innerText;
This will be posted back to the server, since it's a form element. Then you can access the value server-side:
string a = Hidden1.Value;
ID="Label1" for ASP.NET is server side, but for javascript we need a client side ID ie "<%=Label1.ClientID%>"

$find("<%= RadComboBox.ClientID %>") returns null after using an asp:button as the ControlID of a telerik:AjaxUpdatedControl

.Net 4.0
Telerik RadControls for ASP.NET Ajax version: 2013.3.1015.40
I'm using telerik:RadAjaxManager to update a RadGrid and RadComboBox after calling a server method via an asp:button. Once the grid has loaded, it calls the below javascript which is a snippet of the function that checks for any checked boxes client side. If I use the asp:button as the AjaxControlID to update RadComboBox, the method updates the combobox but var ddl returns null and I get the error "Uncaught TypeError: Cannot call method 'get_items' of null". However, if I update the RadComboBox via the OnNeedDataSource event of the updating RadGrid, I get the opposite. RadComboBox doesn't update, even though the method ran, but ddl populates as expected and the javascript methods can run.
function GridLoaded(sender, args) {
var ddl = $find("<%= RadComboBox.ClientID %>");
var items = ddl.get_items();
...
}
Which evaluates to:
function GridLoaded(sender, args) {
var ddl = $find("ctl00_PrimaryContent_RadComboBox");
var items = ddl.get_items();
...
}
I've tried encapsulating the javascript section in a RadCodeBlock and RadScriptBlock based on numerous other presented solutions with no improvement.
This functionality is working on a separate page with the only difference being the ComboBox is called from OnSelectedIndexChanged from one RadGrid to update another RadGrid.
I've checked here with no solution.
telerik RadComboBox find Returns null - why?
I finally figured this one out got it working.
Apparently, RadAjaxManager wants to update the ComboBox as well for everything to work together.
<telerik:RadAjaxManager ID="RadAjaxManager" runat="server" UpdatePanelsRenderMode="Inline">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadAjaxManager">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadComboBox" />
<telerik:AjaxUpdatedControl ControlID="RadGrid" />
</UpdatedControls>
</telerik:AjaxSetting>
...
</AjaxSettings>
</telerik:RadAjaxManager>
If anyone can provide me a credible reason as to why this is, I will gladly mark it as the answer. Otherwise, I hope this prevents frustration for someone else.

Chnage asp.net button text permanently using Javascript

Hi hope this is an easy one. So help me.
i have asp.net button. based upon the input values given to javascript function I want to change the asp.net button value permanently. Even if the page post backs, it should not affect.
What I understood from the above description is you want to change the "Button" text through java script and it should not change, when user post-back page to server. If yes then this solution might helpful for you but below solution will not work, if browser closed and open again.
According to me the best way to persist the value is storing into hidden field, which will be posted every time when your page post backs. So it will never change until your code will not modified it for e.g.:
**ASPX PAGE :**
asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick="javascript:xyz()" />
<asp:HiddenField ID="HiddenField1" runat="server" />
**JavaScript:**
<script>
var value = document.getElementById("HiddenField1").value;
document.getElementById("Button1").value = value;
function xyz() {
document.getElementById("HiddenField1").value = 'world';
}
</script>
**Code Behind [C#]:**
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HiddenField1.Value = "Hello";
}
}
In an above code, when user clicks button then its value (World) will stored into hidden field and set as title through javascript otherwise it will display default value (Hello).
hope this helps !!
It would probably be the easiest using jquery. The code will look like this:
$(document).ready(function() {
$("#button_id").val(new_value);
});

Categories

Resources