locked
User Control Value is lost in code behind file on Postback RRS feed

  • Question

  • User769474054 posted

    I have a custom date selector that I am dynamically adding to the page where the user selects his date and submits the page. below is the code for the user control .ascx

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RequestDateControl.ascx.cs" Inherits="Proj.UI.UserControls.RequestControls.RequestDateControl" %>
    <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %> 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
            <ContentTemplate>     
            <table width="">                 
                 <tr>
                    <td>
                        <asp:Label runat="server" Text="*" ForeColor="Red" ID="reqLabel" EnableTheming="false" ></asp:Label>
                    </td>
                    <td>
                        <asp:Label ID="CaptionLabel" runat="server" Text="Needed By" Width="130px"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="RequestDate" runat="server" Width="200px" onchange="UpdateControls(this);" ></asp:TextBox>
                    </td>
                    <td>
                         <asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" 
                        Enabled="True" TargetControlID="requestDate">
                    </asp:CalendarExtender>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage=" Input is required."
                        ControlToValidate="requestDate" ForeColor="Red">!</asp:RequiredFieldValidator>
                    </td>
                </tr>        
            </table> 
    
            </ContentTemplate>
    </asp:UpdatePanel>

    And ascx.cs

    public partial class RequestDateControl : BaseUserControl
        {
            public string Text
            {
                get
                {
                    if (ViewState["RequestDate"] == null)
                        ViewState["RequestDate"] = this.RequestDate.Text;
                    return ViewState["RequestDate"] as string;
                }
                set
                {
                    ViewState["RequestDate"] = value;
                    this.RequestDate.Text = value;
                }
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                this.RequestDate.Attributes.Add("readonly", "readonly");
                this.RequestDate.Style.Add("color", "gray");
                this.RequiredFieldValidator2.ErrorMessage = Key + " is required!";
            }
            protected void ChangeButton_Click(object sender, EventArgs e)
            {
    
            }
    
            public string DisplayNames
            {
                get { return this.CaptionLabel.Text; }
                set { this.CaptionLabel.Text = value; }
            }
            public bool IsRequired
            {
                get{
                    return this.RequiredFieldValidator2.Enabled;
                }
                set {
                    this.RequiredFieldValidator2.Enabled = value;
                    if(value.Equals(false))
                        this.reqLabel.Style.Add("visibility", "hidden");
                    }
            }
            public string Key { get; set; }
        }

    On the page I used this control, this control gets the correct post back value for Text property only for the first time the page is loaded and submitted. upon next submits on the same page the control uses the value ONLY from first postback.

    For Eg: if I have abc.aspx and I submit the page once with Date of 01/07/2019 for the first time. it saves correctly.Then if I change the date to 01/6/2019 and submit it, the next time it still saves the date as 01/7/2019. At this point, I have to refresh the page to make it work correctly. I am not sure what is missing here.

    Monday, January 7, 2019 9:53 PM

Answers

  • User839733648 posted

    Hi pavanlalit,

    According to your description and code, I've tried to reproduce your problem but failed.

    Since I'm not clear what is the code when you submit the date, I've added a button close to the textbox to make a test.

    My testing code is as following.

    aspx.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserControlValue.aspx.cs" Inherits="WebApplicationForm.UserControlValue" %>
    <%@ Register TagPrefix="DC" TagName="DateControl" src="~/RequestDateControl.ascx"%>
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <DC:DateControl ID="idDC" runat="server" />
            </div>
        </form>
    </body>
    </html>

    ascx.

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RequestDateControl.ascx.cs" Inherits="WebApplicationForm.WebUserControl1" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table width="">
                <tr>
                    <td>
                        <asp:Label runat="server" Text="*" ForeColor="Red" ID="reqLabel" EnableTheming="false"></asp:Label>
                    </td>
                    <td>
                        <asp:Label ID="CaptionLabel" runat="server" Text="Needed By" Width="130px"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="RequestDate" runat="server" Width="200px"></asp:TextBox>
                        <asp:Button  ID="btn" runat="server" OnClick="btn_Click" Text="test1111"/>
                    </td>
                    <td>
                        <ajaxToolkit:CalendarExtender ID="TextBox1_CalendarExtender" runat="server"
                            Enabled="True" TargetControlID="requestDate"></ajaxToolkit:CalendarExtender>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage=" Input is required."
                            ControlToValidate="requestDate" ForeColor="Red">!</asp:RequiredFieldValidator>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>

    ascx.cs

        public partial class WebUserControl1 : System.Web.UI.UserControl
        {
            public string Text
            {
                get
                {
                    if (ViewState["RequestDate"] == null)
                        ViewState["RequestDate"] = this.RequestDate.Text;
                    return ViewState["RequestDate"] as string;
                }
                set
                {
                    ViewState["RequestDate"] = value;
                    this.RequestDate.Text = value;
                }
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                this.RequestDate.Attributes.Add("readonly", "readonly");
                this.RequestDate.Style.Add("color", "gray");
                this.RequiredFieldValidator2.ErrorMessage = Key + " is required!";
            }
    
            public string DisplayNames
            {
                get { return this.CaptionLabel.Text; }
                set { this.CaptionLabel.Text = value; }
            }
            public bool IsRequired
            {
                get
                {
                    return this.RequiredFieldValidator2.Enabled;
                }
                set
                {
                    this.RequiredFieldValidator2.Enabled = value;
                    if (value.Equals(false))
                        this.reqLabel.Style.Add("visibility", "hidden");
                }
            }
            public string Key { get; set; }
    
            protected void btn_Click(object sender, EventArgs e)
            {
                var a = RequestDate.Text;            
            }
        }

    I've changed the date and debug that the date is updated successfully.

    Besides, I wonder that what is the code related to onchange="UpdateControls(this);", maybe this is the reason causing the result.

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 8, 2019 9:04 AM
  • User475983607 posted

    Most likely you are forgetting to set the User Contorl's Text property when the date changes.  You're left with the server controls's view state value.  Try setting a break point to debug your code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 8, 2019 9:36 PM

All replies

  • User839733648 posted

    Hi pavanlalit,

    According to your description and code, I've tried to reproduce your problem but failed.

    Since I'm not clear what is the code when you submit the date, I've added a button close to the textbox to make a test.

    My testing code is as following.

    aspx.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserControlValue.aspx.cs" Inherits="WebApplicationForm.UserControlValue" %>
    <%@ Register TagPrefix="DC" TagName="DateControl" src="~/RequestDateControl.ascx"%>
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                <DC:DateControl ID="idDC" runat="server" />
            </div>
        </form>
    </body>
    </html>

    ascx.

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RequestDateControl.ascx.cs" Inherits="WebApplicationForm.WebUserControl1" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table width="">
                <tr>
                    <td>
                        <asp:Label runat="server" Text="*" ForeColor="Red" ID="reqLabel" EnableTheming="false"></asp:Label>
                    </td>
                    <td>
                        <asp:Label ID="CaptionLabel" runat="server" Text="Needed By" Width="130px"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="RequestDate" runat="server" Width="200px"></asp:TextBox>
                        <asp:Button  ID="btn" runat="server" OnClick="btn_Click" Text="test1111"/>
                    </td>
                    <td>
                        <ajaxToolkit:CalendarExtender ID="TextBox1_CalendarExtender" runat="server"
                            Enabled="True" TargetControlID="requestDate"></ajaxToolkit:CalendarExtender>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage=" Input is required."
                            ControlToValidate="requestDate" ForeColor="Red">!</asp:RequiredFieldValidator>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>

    ascx.cs

        public partial class WebUserControl1 : System.Web.UI.UserControl
        {
            public string Text
            {
                get
                {
                    if (ViewState["RequestDate"] == null)
                        ViewState["RequestDate"] = this.RequestDate.Text;
                    return ViewState["RequestDate"] as string;
                }
                set
                {
                    ViewState["RequestDate"] = value;
                    this.RequestDate.Text = value;
                }
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                this.RequestDate.Attributes.Add("readonly", "readonly");
                this.RequestDate.Style.Add("color", "gray");
                this.RequiredFieldValidator2.ErrorMessage = Key + " is required!";
            }
    
            public string DisplayNames
            {
                get { return this.CaptionLabel.Text; }
                set { this.CaptionLabel.Text = value; }
            }
            public bool IsRequired
            {
                get
                {
                    return this.RequiredFieldValidator2.Enabled;
                }
                set
                {
                    this.RequiredFieldValidator2.Enabled = value;
                    if (value.Equals(false))
                        this.reqLabel.Style.Add("visibility", "hidden");
                }
            }
            public string Key { get; set; }
    
            protected void btn_Click(object sender, EventArgs e)
            {
                var a = RequestDate.Text;            
            }
        }

    I've changed the date and debug that the date is updated successfully.

    Besides, I wonder that what is the code related to onchange="UpdateControls(this);", maybe this is the reason causing the result.

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 8, 2019 9:04 AM
  • User769474054 posted

    Hi Jennifer,

    The Submit button is on the Page where this control is used, not in the user control itself.

    And UpdateControl(this) method is pasted below.

    function UpdateControls(ss) {
        if (ss != null) {
    
            var controlIdWithParentIds = $(ss).attr('id').split("_");
            var actualControlId = controlIdWithParentIds[controlIdWithParentIds.length - 1];
            var url = "";
            var dataString = "";
            var curLibId = GetQueryStringParams("libid");
            if (actualControlId.indexOf("Severity") >= 0) {
                url = "Request.aspx/SeverityToDateNeeded";
                dataString = "{'libraryId':'" + curLibId + "','severity' :'" + ss.value + "'}";
            }
            else {
                url = "Request.aspx/NeededByToSeverity";
                dataString = "{'libraryId':'" + curLibId + "','dateNeededString' :'" + ss.value + "' ,'controlId' :'" + $(ss).attr('id') + "'}";
            }
    
            $.ajax({
                type: 'POST',
                url: url,
                data: dataString,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $.each(response.d, function (index, currentControl) {
    
                        if (currentControl.ControlName.indexOf("Physical") > -1) {
                            ($('[id$="GeneralInformationControl_Physical_Needed_By_RequestDate"]').get(0)).value = currentControl.ControlValue;
                        }
                        else if (currentControl.ControlName.indexOf("Step") > -1) {
                            ($('[id$="GeneralInformationControl_Step_Needed_By_RequestDate"]').get(0)).value = currentControl.ControlValue;
                        }
                        else if (currentControl.ControlName.indexOf("IPN") > -1) {
                            ($('[id$="GeneralInformationControl_IPN_Needed_By_RequestDate"]').get(0)).value = currentControl.ControlValue;
                        }
                        else if (currentControl.ControlName.indexOf("Logical") > -1) {
                            ($('[id$="GeneralInformationControl_Logic_Needed_By_RequestDate"]').get(0)).value = currentControl.ControlValue;
                        }
                        else if (currentControl.ControlName.indexOf("Severity") > -1) {
                            selectItemByValue(($('[id$="GeneralInformationControl_Severity"]').get(0)), currentControl.ControlValue);
                        }
    
                    });
                    ToggleManagerCheckBox(($('[id$="GeneralInformationControl_Severity"]').get(0)).value);
                },
                processData: 'false'
            });
    
        }
    }

    The problem here is the control takes the correct value for the date only on the first post back. when you postback the page without refreshing after the first postback, the control gets the same value it used in the first post back not the one that is sent in the second postback. Hope I am clear about my issue now.

    Kindly let me know if you have any questions here or need anything from me. very grateful for the help :)

    Tuesday, January 8, 2019 5:48 PM
  • User475983607 posted

    Most likely you are forgetting to set the User Contorl's Text property when the date changes.  You're left with the server controls's view state value.  Try setting a break point to debug your code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 8, 2019 9:36 PM
  • User769474054 posted

    This seems the issue. In my code we have

    if (this.CurrentRequestId != 0 && !Page.IsPostBack)
                {
                    control.Text = this.GetRequestAttributeValue(c.AttributeKey);
                }

    when dynamically adding the control to the page. it worked as I removed the !IsPostBack check.

    Tuesday, January 8, 2019 10:35 PM