hidden field value lost after postback - asp.net

I have two hidden controls:
<asp:HiddenField runat="server" id="pageHeader" />
<asp:HiddenField runat="server" id="pageInformation" />
I am calling following function from master page:
show_tip(this, document.getElementById('ctl00_pageInformation').value, document.getElementById('ctl00_pageHeader').value);
and i am passing values in hidden field on .cs page in page load as follows:
string message = Request.Form["pageInformation"];
if (string.IsNullOrEmpty(message))
{
((HiddenField)Master.FindControl("pageHeader")).Value = pageHeading;
((HiddenField)Master.FindControl("pageInformation")).Value = pageInformation;
}
This is working fine, but on page POSTBACK, hidden fields lose their value. How can I retain the values after postback?

OK this is what you do.
Two functions and a hidden field. The first functions in JS adds a handler which gets the values from the hidden fields and stores them in variables. The second function in JS adds a handler which gets the values from the variables and puts them back into the hidden fields.
<script type="text/javascript">
var txt1;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
txt1 = $get('<%= hdntxt1.ClientID%>').value;
}
function EndRequestHandler(sender, args) {
$get('<%= hdntxt1.ClientID%>').value = txt1;
}
</script>
<asp:HiddenField runat="server" ID="hdntxt1" Value="" />
You don't actually need to use hidden fields however if other parts of the form need to obtain the values then those values will be handy at any time regardless of postbacks!

I guess your hidden field value is getting reset on post back.
Try keeping your code inside if block cheking for postback
if(!ispostback)
{
string message = Request.Form["pageInformation"];
if (string.IsNullOrEmpty(message))
{
((HiddenField)Master.FindControl("pageHeader")).Value = pageHeading;
((HiddenField)Master.FindControl("pageInformation")).Value = pageInformation;
}
}

Related

Possible solution to UpdatePanel and ClientIDMode="Static"

I've been looking everywhere for a solution to the static ClientIDMode + UpdatePanel in Asp.NET, as seen in http://connect.microsoft.com/VisualStudio/feedback/details/584991/clientidmode-static-in-updatepanel-fails-to-do-async-postback
The problem is in the Sys.WebForms.PageRequestManager.uniqueIDToClientID function, that converts names to id by replacing "$" characters to "".
I made a fix that seems to work but I want you guys to tell me what you think and if I'm missing something. Thanks a lot!
var old_uniqueIDToClientID = Sys.WebForms.PageRequestManager.prototype._uniqueIDToClientID;
Sys.WebForms.PageRequestManager.prototype._uniqueIDToClientID = function (arg) {
var element = this._form.elements[arg];
return (element) ? element.id : old_uniqueIDToClientID(arg)
}
We made a similar fix, but we changed another function that was involved in the search for the element that caused the postback.
We have placed the following code at the bottom of our master page to make sure that it is included after the scriptmanager has loaded its scripts. Essentially it keeps modifying the id until it finds the element that caused the postback. The original code searched for the element by removing tokens from the right hand side of the name delimited by the dollar sign. So "$ctl00$ddl001" would become "$ctl00". If you are using static ids then that suffix might never exist. We modified the function to start from the left and remove the container names until an element is found.
It seems to work for us for now. :)
if (Sys.WebForms.PageRequestManager) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm._findNearestElement = function (uniqueID) {
while (uniqueID.length > 0) {
var clientID = this._uniqueIDToClientID(uniqueID);
var element = document.getElementById(clientID);
if (element) {
return element;
}
var indexOfFirstDollar = uniqueID.indexOf('$', 1);
if (indexOfFirstDollar === -1) {
return null;
}
uniqueID = uniqueID.substring(indexOfFirstDollar + 1, uniqueID.length);
}
return null;
};
}
An updatepanel to work in asychronous mode you need to add a scriptmanager tag in the form.
<asp:ScriptManager EnablePartialRendering="true"
ID="ScriptManager1" runat="server"></asp:ScriptManager>
or you can add triggers
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl_Manufacturer" EventName="SelectedIndexChanged" />
</Triggers>

Getting the value of a hidden field

I have an ASP.NET page with three hidden fields. (Just one would do if I can get it to work. Just showing that I've tried several things.)
<input type="hidden" id="hiddenSkillId1" runat="server" />
<input type="hidden" id="hiddenSkillId2" />
<asp:HiddenField ID="hiddenSkillId3" runat="server"/>
I also have a JavaScript function that is being called by an AJAXControlToolKit.AutoCompleteExtender.OnClientItemSelected event:
<script type="text/javascript">
function SkillPartialMatchSelected(source, eventArgs ) {
document.getElementById("ctl00_Content_hiddenSkillId1").Value = eventArgs.get_value();
document.getElementById("hiddenSkillId2").Value = eventArgs.get_value();
document.getElementById("ctl00_Content_hiddenSkillId3").Value = eventArgs.get_value();
}
</script>
Using a break point and inspecting the values, I have confirmed that the vales are being set on the Client side.
Finally I have C# code behind for the page that is connected to a LinkButton OnClick event.
protected void AddSkillToProspect(object sender, EventArgs e)
{
string selectedKey1 = Request.Form[hiddenSkillId1.ClientID];
string selectedKey2 = Request.Form["hiddenSkillId2"];
string selectedKey3 = Request.Form[hiddenSkillId3.ClientID];
string selectedItem = SkillNameBox.Text.Trim();
...
}
All three selectedKey values are null but the selectedItem value from the ASP.NET Text Edit has a value.
From what I've read, one of these should work. Am I missing something? What can I do to get the value from a JavaScript function on the client side back to the server side?
The problem is related to case-sensitivity in JavaScript. Although you have set the .Value for these fields, that is not the same as the .value. Change your javascript to set the .value and you should be all set.
<script type="text/javascript">
function SkillPartialMatchSelected(source, eventArgs )
{
document.getElementById("ctl00_Content_hiddenSkillId1").value = eventArgs.get_value();
document.getElementById("hiddenSkillId2").value = eventArgs.get_value();
document.getElementById("ctl00_Content_hiddenSkillId3").value = eventArgs.get_value();
}
</script>
your hiddens controls have runat=server on them means they are server control and you can access them by their id in your code behind
this way the difference will hiddenSkillId1 is a htmlserver control, hiddenSkillId2 normal html control and this one hiddenSkillId3 is an asp.net control
string selectedKey1 = hiddenSkillId1.Value;
string selectedKey3 = hiddenSkillId3.Text;
string selectedKey2 = Request.Form[hiddenSkillId2];
So please try using it this way

CustomValidator using CustomValidationScript

I have an ASP.NET TextBox with a CustomValidation control that invokes client side validation script.
<asp:TextBox ID="txtSubsContrRbtAmt" runat="server"
CssClass="textEntry NumericInput" Width="150px"
Text="" onKeyUp="SumValues();" MaxLength="16"></asp:TextBox>
<asp:CustomValidator ID="cvalSubsContrRbtAmt" runat="server" ClientValidationFunction="ValidatetxtSubsContrRbtAmt"
ControlToValidate="txtSubsContrRbtAmt" CssClass="errlable" ErrorMessage="Max Decimals = 7"
SetFocusOnError="True" ValidationGroup="CarbsAdd"></asp:CustomValidator>
Here's the Client script:
function ValidatetxtSubsContrRbtAmt(source, args) {
var txtSubsContrRbtAmt = document.getElementById("<%=txtSubsContrRbtAmt.ClientID%>");
var amount = txtSubsContrRbtAmt.value;
args.IsValid = ValidAmount(amount);
if (!args.IsValid)
txtSubsContrRbtAmt.focus();
}
function ValidAmount(amount) {
if (isNumber(amount)) {
return (RoundToXDecimalPlaces(amount, 7) == amount);
}
else {
return true;
}
In the ValidatetxtSubsContrRbtAmt function, the "source" parameter is the CustomValidator. That control has a property "ControlToValidate." If I can get to it, I can programmatically retrieve the value from that control and not have to have a separate function to validate each textbox.
jQuery is too much for me at this point, I'm looking for a plain old Javascript approach, please.
You don't have to get the text box. You can get the value from args.Value. The focus should be set automatically if you set SetFocusOnError="true".
function ValidatetxtSubsContrRbtAmt(source, args) {
var amount = args.Value;
args.IsValid = ValidAmount(amount);
}
You should be able to get to the control from the source object.
function ValidatetxtSubsContrRbtAmt(source, args) {
var controlToFocusOn = source.ControlToValidate;
you can switch that out with "document.getElementByID()" to get the ID or whatever attribute you need
var controlId = document.getElementById(source.ControlToValidate).id;
}
now you can focus or do what you need with the control. I had to access the the actual ControlToValidate earlier today from a CustomValidator.

Telerik RadWindow Javascript return values to ASP.NET

I have a parent page that launches a telerik radwindow and passes it an argument.
Once the radwindow is done processeing the value, I need it to return it to the parent page, and I would like the parent page to have access to this value in my code behind page.
I have tried to pass the value to a hidden field on my page and then trigger a page refresh and my code behind watches to see if the value is working.
I can't seem to get this to work. I get the return value in the parent javascript, but i can't get it from my hidden field from the code behind.
I even get it into the text box like i need to but, when i find the Hidden field in the codebehind, there is no value set.
Where I have set alerts, I am getting the values displayed as i need to.
I suspect that the reason I can't see my return value in the code behind file, is that when the page is refreshed, I am getting a new page and not only causing a post back.
And is there not a better way i can do this.
here is my code in the parent page:
Parent ASPX:
<script type="text/javascript">
function OpenWnd() {
var oWnd = radopen(null, "RadWindow1");
}
function OnClientShow(oWnd) {
//Create a new Object to be used as an argument to the radWindow
var arg = new Object();
//Using an Object as a argument is convenient as it allows setting many properties.
arg.text = document.getElementById("TextBox1").value;
//Set the argument object to the radWindow
oWnd.Argument = arg;
}
function ClientCallBackFunction(radWindow, returnValue) {
//check if a value is returned from the dialog
if (returnValue.newtext) {
document.getElementById("Hidden1").value = returnValue.newtext;
alert("HiddenValue: " + document.getElementById("Hidden1").value);
}
}
</script>
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<div>
<telerik:RadWindowManager ID="RadWindowManager2" runat="server">
<Windows>
<telerik:RadWindow ID="RadWindow1" runat="server" OnClientShow="OnClientShow" ClientCallBackFunction="ClientCallBackFunction"
NavigateUrl="Dialog2.aspx" />
</Windows>
</telerik:RadWindowManager>
</div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
<input type="button" value="Send content to dialog page" onclick="OpenWnd()" />
<p>
<input id="Hidden1" type="hidden" runat="server" />
</p>
</form>
Parent Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
HtmlInputHidden hidden = (HtmlInputHidden)Page.FindControl("Hidden1");
if (IsPostBack && !string.IsNullOrEmpty(hidden.Value))
{
//Code Here
}
}
Here is my Dialog code:
Dialog ASPX:
<script type="text/javascript">
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function ConfigureDialog() {
//Get a reference to the radWindow wrapper
var oWindow = GetRadWindow();
//Obtain the argument
var oArg = oWindow.Argument;
//Use the argument
var oArea = document.getElementById("TextBox1");
oArea.value = oArg.text;
}
function SendAndClose() {
var oWindow = GetRadWindow();
//Get current content of text area
var arg = new Object();
arg.newtext = document.getElementById("TextBox1").value;
oWindow.Close(arg);
RefreshParentPage();
}
function RefreshParentPage() {
GetRadWindow().BrowserWindow.location.reload();
alert("RefreshParentPage");
}
</script>
Thanks for all the help
Ian
You are doing the following
GetRadWindow().BrowserWindow.location.reload();
But that wont cause a postback it will simply reload the parent page, you need to cause a potback.
You could try adding a button to the parent form with the style set 'display:none', and handling the click event in the code behind, you can fire this button off from your js code.
In Parent Page :
<asp:Button runat="server" id="btnClick" Style="display:none" OnClick="btnClick_Click"/>
protected void btnClick_Click(object sender,EventArgs e)
{
string val = this.Hidden1.Value; //Code goes here
}
You can invoke from your javascript like this (non jQuery), place this in your callback
document.getElementById('<%= btnClick.ClientID').click();
A better approach would be this on the aspx side:
<%=this.ClientScript.GetPostBackEventReference(new System.Web.UI.PostBackOptions(btnClick))%>

ASPXGridView Custom CallBack

We have the DevExpress grid and in the OnCustomCallback event we need to assign a hidden field value=true. After we need to get the hidden field value to javascript?
We tried in following manner:
protected void dgUnReconcile_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
{
ASPxGridView temp = ((DevExpress.Web.ASPxGridView.ASPxGridView)(sender));
string gridInstancename = ((DevExpress.Web.ASPxGridView.ASPxGridView)(sender)).ClientInstanceName;
if (gridInstancename.Equals("grid"))
{
List<Object> selected = dgUnReconcile.GetSelectedFieldValues(new[] { "Key" });
if (selected.Count > 0)
{
existingKey = true;//hidden field value
}
}
}
We need to access the hidden fields value through javascript
var ='<%# existingKey%>';
It always shows empty value.
Try to use the JSProperties of the grid:
aspx:
<dxwgv:ASPxGridView ID="myGridView" ClientInstanceName="myGridView" runat="server">
</dxwgv:ASPxGridView>
sets the value in code-behind (C#):
myGridView.JSProperties["cpMyValue"] = "hello, world!";
gets the value on client (js):
alert(myGridView.cpMyValue);
To change other controls during a server-side event, you might need to disable callbacks (see the ASPxGridView.EnableCallBacks property) and place both the hidden field and grid control into the UpdatePanel.
Alternatively, you can do it on the client-side with javascript if you want to keep callbacks enabled. There's a similiar sample project attached here:
http://www.devexpress.com/Support/Center/p/Q201214.aspx

Resources