Unable to read hidden field value from server side - javascript

I have a aspx page (default.aspx), inside which I am loading a user control (tree.ascx).
inside the tree.ascx there is a hidden field.
<asp:HiddenField ID="HiddenField1" runat="server"/>
I am assigning a value to the hidden field using javascript.
document.getElementById('<%=HiddenField1.ClientID%>').value = "some text here";
alert(document.getElementById('<%=HiddenField1.ClientID%>').value);
document.getElementById('form1').submit();
The alert displays the value absolutely fine. which means the value gets inserted in the hidden field properly.
But when I am posting back to server and checking the value, it is always null.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// do something.
}
else
{
string str = this.HiddenField1.Value;
}
}
My code is always getting a empty string here. somehow the postback is erasing the value from the hidden field.
What could be the reason?

Try using below syntax. It works for me even after postback.
ASPX code
<asp:HiddenField runat="server" ID="aspHiddenField" />
<input type="hidden" id="inputHidden" value='<%= aspHiddenField.ClientID %>' />
JavaScript Code
var inputHidden = document.getElementById('inputHidden');
$("#" + inputHidden.value).val("some text");
Code Behind
if (!string.IsNullOrEmpty(aspHiddenField.Value))
{
//Your code goes here
}

Check if your control is within a master page, if it is, then you need to access it like that, 1st Master Page->within master page look for the control's value, it will work surely.

Place your hidden field in update panel like :
<asp:UpdatePanel ID="UpnlHidden" runat="server">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
This will work for you :-)

Related

How do I call a C# method using JavaScript in .NET Framework 4.7.2?

Whenever the textbox value changes a C# method should be called. The textbox uses a calendar validator so when a user changes the date it should count as a value change. The date can be changed by clicking on a new date or typing it in. Typing it in can possibly call the method multiple times which is fine. How can I activate a C# method whenever a textbox value is changed using JavaScript in .NET Framework 4.7.2?
.ascx file:
<script type="text/javascript">
$(document).ready(function () {
$("#textBox1).change(function () {
// How can I call the buttonClick method?
}
});
</script>
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="date" runat="server" ControlToValidate="textBox1"
ErrorMessage="Date Required" CssClass="field-validation-error"></asp:RequiredFieldValidator>
<ajax:CalendarExtender ID="ceDate" runat="server" TargetControlID="textBox1" />
.ascx.cs file:
protected void buttonClick(object sender, EventArgs e)
{
//...
}
I tried doing this without JavaScript. There is an OnTextChanged event listener that should call the buttonClick method. This has not been working for me. Clicking on a new date or typing in the textbox doesn't trigger the method. It only seems to trigger when I press the 'Enter' key. The event listener should not depend on the 'Enter' key being pressed.
.ascx file:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick"></asp:TextBox>
<asp:RequiredFieldValidator ID="date" runat="server" ControlToValidate="textBox1"
ErrorMessage="Required" CssClass="field-validation-error"></asp:RequiredFieldValidator>
<ajax:CalendarExtender ID="ceDate" runat="server" TargetControlID="textBox1" />
Method 1:
<script type="text/javascript">
$(document).ready(function () {
$("#textBox1").change(function () {
<%= Page.ClientScript.GetPostBackEventReference(textBox1, "") %>
}
});
</script>
But take care that under certain circumstances, the id value of the text box control will not necessarily be the same as the ID (name) of the textbox control on the server side. One way to make sure that your jQuery selector uses the correct value for the id of the textbox control is to use the ClientID property of the server-side object, like so:
<script type="text/javascript">
$(document).ready(function () {
$("#<%= textBox1.ClientID %>").change(function () {
<%= Page.ClientScript.GetPostBackEventReference(textBox1, "") %>
}
});
</script>
Or if you don't want to bother with using the ClientID property, then you can set the value of ClientIDMode attribute on the mark-up of the control to Static, then the id on the server and client will always be the same, like so:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick" ClientIDMode="Static"></asp:TextBox>
However, it is not advisable to use ClientIDMode="Static" within custom user controls, since you could end up with multiple elements with the same ID on the client when the control is used multiple times on the same page.
Method 2:
It is also possible to achieve all this without using JavaScript.
The buttonClick server-side event handler will not be called until the form is posted back to the server-side.
One way to automatically do a post-back to the server whenever the text is changed is by adding the AutoPostBack="true" attribute to the mark-up of the textBox1 control:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick" AutoPostBack="true"></asp:TextBox>
Side-note: Remember, doing a post-back will cause the whole page/control life-cycle to be executed, even if your controls are within an <asp:UpdatePanel>...</asp:UpdatePanel> block (for asynchronous/ajax updates), so things like the Page_Load function will be run every time there is a post-back. If you have initialization code within such functions and you don't want to re-initialize on every post-back, just check that the Request is not post-back before running initialization code, i.e:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// initialization
}
}

ASP.Net get ScriptManager.RegisterClientScriptBlock return on UpdatePanel hiddenField

I am trying to obtain the return of a Javascript function that I call ont server side using ScriptManager.RegisterClientScriptBlock .
Currently, my javascript function save the value in a HiddenField that is contained in an UpdatePanel. When I call the method , I run the ScriptManager.RegisterClientScriptBlock and after that get the value of the HiddenField , but always returns me the value of the previous call. Here I show the code:
My User Control ASPX Side:
<script>
var num = 0;
function getReturn() {
num = num + 1;
var hr= document.getElementById('<%= hdf.ClientID %>');
hRetorno.value = num;
}
</script>
...
<asp:UpdatePanel ID="up1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:HiddenField ID="hdf" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
My User Control Server Side Code:
public String GetReturn()
{
return MyControl.jsGetReturn(this.Page, this.hdf);
}
private static String jsGetReturn(Page page, HiddenField hid)
{
ScriptManager.RegisterStartupScript(page, page.GetType(), "key", "getReturn();", true);
return hid.Value;
}
Index Page ASPX Side:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="width:720px; height:480px;">
<uc1:MyControl runat="server" id="MyControl1"/>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
<asp:TextBox ID="txt" runat="server" ></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
Index Page Server Side Code:
protected void btn_Click(object sender, EventArgs e)
{
txt.Text = MyControl1.GetReturn();
}
You can not do these things simultaneously.
Set value of hidden field from server side code using javascript via RegisterClientScriptBlock or RegisterStartupScript.
And retrieve that hidden filed value in server side code at the same time.
This is because, (changed) hidden field value is available to server-side code only when there is postback, when you set the value from server-side, there is no postback happening, that is why you are always getting previous value , i.e. that old value which is posted back to page.
EDIT
When you invoke RegisterClientScriptBlock or RegisterStartupScript, it won't make JS call instantly, rather it just append a javascript call before or after <form.. tag based on what you used and they are called on document load, so that means in jsGetReturn when you call RegisterStartupScript, it will set value of hidden field in document load, - hid.Value will not have updated value, as it is yet to be incremented via document load.

setting label value in javascript

I have code like this
<table>
<tr>
<td>
<div>
<asp:Label runat="server" ID="lblBookmarksIds" Style="visibility: hidden;" Text="test"/>
</div>
</td>
<td>
<asp:UpdatePanel runat="server" ID="buttonPanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button runat="server" ID="btnInvokeImageRead" CausesValidation="false" UseSubmitBehavior="false"
OnClick="btnInvokeImageRead_Click" Style="visibility: hidden;" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
in javascript i'm trying to set value of label and call codebehind function so that i will have desired value passed to codebehind like that :
alert(document.getElementById('<%= lblBookmarksIds.ClientID%>').firstChild.nodeValue);
document.getElementById('<%= lblBookmarksIds.ClientID%>').innerText = str;
alert(document.getElementById('<%= lblBookmarksIds.ClientID%>').firstChild.nodeValue);
//alert('1');
if (str != "") {
document.getElementById('<%= btnInvokeImageRead.ClientID%>').click();
}
when second alert gets displayed the value of lblBookmarksIds has changed value, but when i debug in codebehind function btnInvokeImageRead_Click the value of lblBookmarksIds has its old value.
Anybody knows Why ?
Regards
Wojciech
Labels are not passed to code behind. You will have to use an input(TextBox) for that purpose.
You can style an input to look like a label using CSS.
Alternatively, you can keep the value in a hidden field, and use javascript to show the value in a label and pass it back in the hidden field.
The reason ASP.NET is able to "see" the values entered into a TextBox and similar controls is because the values of these controls are sent in the POST body when the page posts back. You can see this through any number of tools, including the Developer Tools your browser likely includes or an intercepting proxy like Fiddler. When the postback occurs, each of those controls has a LoadPostData function that processes the POST data and updates the Text properties (or whatever properties) of the control.
The contents of a Label are not submitted in the POST data, so .NET has no way to see any changes made to it from JavaScript.
The controls that do process post data all implement IPostBackDataHandler.

ASP.Net session not updated in javascript

when my button is clicked I fire the javascript to get the session..
But value of session not updated...
alert('<%= Session["file"]%>');
It won't be up to date if its changed after the page is rendered.
You might want to look at page methods (an ajax system) or another ajax approach.
Any inline code once rendered to the page will not change, which is a normal behavior.
use a Hidden field instead.
mark-up:
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
Session["file"] = "Data Here";
HiddenField1.Value = Session["file"].ToString();
}
javascript:
alert(document.getElementById('<%= HiddenField1.ClientID %>').value);

Enable asp button only when there is text in the asp textbox

Ok, so I have a multiple ASP textboxes and ASP buttons on a page within a multiview.
The submit button associated with each textbox should be enabled only when there is text entered in the textbox. So, I wrote a Javascript function to handle this and I'm getting an error saying "document.getElementById(...)' is null or not an object"
function checkEmptyTxtBox(val, savebtn) {
if (val.value.replace(/^\s+|\s+$/g, "") == "")
document.getElementById(savebtn).disabled = true;
else
document.getElementById(savebtn).disabled = false;
}
<asp:TextBox
ID="txt_Comments_2"
runat="server"
Wrap="true"
TextMode="MultiLine"
onkeyup="checkEmptyTxtBox(this,'<%= btnSave2.ClientID %>')">
</asp:TextBox>
<asp:Button
ID="btnSave2"
runat="server"
text="Save"
Enabled="False"/>
This is on VS2010.
You cannot set an attribute of a Server Side Control using <%= %>. If you look at the rendered source, it looks like this:
onkeyup="checkEmptyTxtBox(this,'<%= btnSave2.ClientID %>')"
It literally contains the <%= %>.
You could set the attribute on page load like this:
protected void Page_Load(object sender, EventArgs e)
{
txt_Comments_2.Attributes["onkeyup"] = "checkEmptyTxtBox(this,'" + btnSave2.ClientID + "')";
}
EDIT:
As many will be willing to point out; this isn't really the "best" way to do event registration in HTML. Rather, the JavaScript should bind to the keyup event by adding an event listener. For example, with jQuery it becomes:
$(document).ready(function() {
$('#<%: txt_Comments_2.ClientID %>').keyup(function() {
if ($(this).val().replace( /^\s+|\s+$/g , "") == "") {
$('#<%: btnSave2.ClientID %>').attr('disabled', 'disabled');
}
else {
$('#<%: btnSave2.ClientID %>').removeAttr('disabled');
}
});
});
And your ASP.NET markup looks like this:
<asp:TextBox
ID="txt_Comments_2"
runat="server"
Wrap="true"
TextMode="MultiLine" />
<asp:Button
ID="btnSave2"
runat="server"
text="Save"
Enabled="False"/>
This has the advantage of not cluttering your HTML with event registration. There are even other, perhaps cleaner ways of doing this with something like KnockoutJS.
This might be because the ID of your button is btnSave2 but you're passing <%= btnSave2.ClientID %> as the savebtn. Javascript cannot find the element by the id which you specified.
Also, I just read up on people who have had a similar issue and theirs was that they did not do a RegisterStartupscript.
Please check these out:
http://forums.asp.net/t/1160208.aspx/2/10?document+getelementbyid+is+null+or+not+an+object
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Categories