UpdatePanel内的标签不会显示代码隐藏分配的值

时间:2016-07-13 00:02:39

标签: javascript c# jquery html asp.net

我在这里结束了我的智慧。我已经为模式定义了一个用户控件,允许用户更改密码。在模式中,字段包含在UpdatePanel中,我想显示有关密码更改请求结果的成功/错误消息。但是,Label控件根本不会改变。

标记:

<script type="text/javascript">
    var reqValidator1;
    var reqValidator2;
    var regValidator;
    var compValidator;

    function configPasswordValidators() {
        reqValidator1 = $("#<%= RequiredFieldValidator1.ClientID %> ")[0];
        reqValidator2 = $("#<%= RequiredFieldValidator2.ClientID %> ")[0];
        regValidator = $("#<%= RegularExpressionValidator1.ClientID %> ")[0];
        compValidator = $("#<%= CompareValidator1.ClientID %> ")[0];
    }

    function enablePasswordValidators() {
        ValidatorEnable(reqValidator1, true);
        ValidatorEnable(reqValidator2, true);
        ValidatorEnable(regValidator, true);
        ValidatorEnable(compValidator, true);
    }

    function disablePasswordValidators() {
        ValidatorEnable(reqValidator1, false);
        ValidatorEnable(reqValidator2, false);
        ValidatorEnable(regValidator, false);
        ValidatorEnable(compValidator, false);
    }

    function showProcessingSpinner() {
        $("#dvChangeUserPasswordBtns").hide();
        $("#dvProcessing").show();
        $("#<%= btnChange.ClientID %>").click();
    }
</script>
<div class="new-container new-modal" id="newContainerPanel">
    <div runat="server" id="credentialManagerModal" class="new-container-inner panel panel-default" style="width: 600px;">
        <div class="panel-heading">
            <h4 class="modal-title">Change Password</h4>
        </div>
        <asp:UpdatePanel runat="server" ID="upnlChangePassword" ChildrenAsTriggers="true" UpdateMode="Always">
            <ContentTemplate>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-3 text-right" style="width: 160px; padding-top: 15px">
                            <asp:Label ID="lblPassword1" runat="server" />
                        </div>
                        <div class="col-md-5" style="margin-left: -20px; margin-right: -20px; padding-top: 8px">
                            <asp:TextBox ID="txtPassword1" runat="server" TextMode="Password" MaxLength="100" Width="260px" CssClass="form-control" />
                        </div>
                        <div class="col-md-4" style="padding-top: 15px;">
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="password" runat="server" ControlToValidate="txtPassword1" SetFocusOnError="true" Display="Dynamic" Enabled="false" Style="margin-left: 40px; color: red;"></asp:RequiredFieldValidator>
                        </div>
                    </div>
                    <div class="row" style="margin-top: 15px;">
                        <div class="col-md-3 text-right" style="width: 160px; padding-top: 7px;">
                            <asp:Label ID="lblPassword2" runat="server" />
                        </div>
                        <div class="col-md-5" style="margin-left: -20px; margin-right: -20px;">
                            <asp:TextBox ID="txtPassword2" runat="server" TextMode="Password" MaxLength="100" Width="260px" CssClass="form-control" />
                        </div>
                        <div class="col-md-4" style="padding-top: 7px;">
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ValidationGroup="password" ControlToValidate="txtPassword2" SetFocusOnError="true" Display="Dynamic" Enabled="false" Style="margin-left: 40px; color: red;"></asp:RequiredFieldValidator>
                        </div>
                    </div>
                    <div class="row" style="padding-top: 15px; text-align: center;">
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationGroup="password" runat="server" ControlToValidate="txtPassword1" SetFocusOnError="true" Display="Dynamic" Enabled="false" Style="margin-left: 30px; color: red;"></asp:RegularExpressionValidator>
                        <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtPassword2" Operator="Equal" Type="String" ValidationGroup="password" ControlToCompare="txtPassword1" Display="Dynamic" EnableClientScript="true" Enabled="false" Style="margin-left: 20px; color: red;"></asp:CompareValidator>
                    </div>
                    <div class="row text-center" style="margin-top: 15px;">
                        <asp:Label runat="server" ID="lblChangePasswordSuccess" ForeColor="MediumSeaGreen"></asp:Label>
                        <asp:Label runat="server" ID="lblChangePasswordError" ForeColor="Red"></asp:Label>
                    </div>
                </div>
                <div id="passwordModalFooter" class="modal-footer">
                    <div id="dvChangeUserPasswordBtns" class="text-center">
                        <button id="btnClose" class="btn btn-default" onclick="HideChangePasswordModal();" style="float: left;">Cancel</button>
                        <button id="btnProcessChange" runat="server" class="btn btn-primary" onclick="showProcessingSpinner();" style="float: right;">Change Password</button>
                    </div>
                    <div class="text-center" id="dvProcessing" style="display: none;">
                        <img src="../Images/progress-spinner.gif" />&nbsp;Processing... 
                    </div>
                    <div style="display: none">
                        <asp:Button ID="btnChange" runat="server" CssStyle="btn btn-primary change-password-button" OnClick="ChangePassword_Click" CausesValidation="true" ValidationGroup="password" />
                    </div>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
</div>

代码背后:

protected void ChangePassword_Click(object sender, EventArgs e)
{
    string retVal = ChangePassword(Request.QueryString["ID"]); // Separate processing method that is working fine.

    if (retVal == "Password changed.")
    {
        lblChangePasswordSuccess.Text = retVal;
        lblChangePasswordError.Text = string.Empty;
    }
    else
    {
        lblChangePasswordSuccess.Text = string.Empty;
        lblChangePasswordError.Text = retVal;
    }
}

母版页中的ScriptManager如下所示:

<asp:ScriptManager ID="ScriptManagerMain" runat="server" EnablePageMethods="True" EnablePartialRendering="True" LoadScriptsBeforeUI="true">

我尝试了什么:

  • 更改UpdatePanel属性。如果我使用ChildrenAsTriggers="true"或手动定义触发器无关紧要。如果UpdateMode使用“始终”或“有条件”,则无关紧要。

  • 从后面的代码中调用UpdatePanel1.Update()无效。

  • 尝试通过javascript调用编辑标签(或我放在其中的任何其他元素类型)也不起作用。 ScriptManager.RegisterStartupScript(upnlChangePassword, this.GetType(), "script", string.Format("DisplayProcessingMessage('{0}');", retVal), true);之类的东西没有效果。

我已经逐步完成了代码,并且所有事件都正常触发,并且返回了正确的值。我在部分回发之前和之后检查了DOM,并且元素始终保持不变。浏览器中未检测到任何javascript错误。

它位于使用母版页的Web表单内的用户控件中。在浏览器中,页面中的内容比在此处发布的内容要多得多,因此我认识到此文件之外可能存在某些内容。但是,如果我至少可以知道应该寻找什么可能会导致这种行为,那将是一个巨大的帮助。

1 个答案:

答案 0 :(得分:1)

只需在更新面板中添加PostBackTrigger

<Triggers>
    <asp:PostBackTrigger ControlID="btnChange" />
</Triggers>

作为一种解决方法,您可以使用发布到C#[WebMethod]的AJAX调用,而不是调用服务器端点击事件。

1.用此替换您的showProcessingSpinner()功能:

function showProcessingSpinner() {

    $("#dvChangeUserPasswordBtns").hide();
    $("#dvProcessing").show();
    //$("#<%= btnChange.ClientID %>").click();

    var id = getQueryStringParamByName("ID");
    alert("Query string parameter value for ID is - " + id);

    $.ajax({
        type: "POST",
        url: "ModalPopupAndUpdatePanel.aspx/ChangePasswordWeb",
        contentType: "application/json;charset=utf-8",
        data: '{id:"' + id + '"}',
        success: function (data) {
            debugger;
            alert('Success Message - ' + data.d.SuccessMessage);
            var successMessage = data.d.SuccessMessage;
            $("#lblChangePasswordSuccess").text(successMessage);
        },
        error: function (errordata) {
            alert('Error.AJAX call failed')
        }
    });
}


function getQueryStringParamByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

2.在名为 ChangePasswordWeb 的代码中创建一个Web方法:

[System.Web.Services.WebMethod]
public static AJAXResponse ChangePasswordWeb(string id)
{
    string retVal = ChangePassword(id);
    var response = new AJAXResponse();

    if (retVal == "Password changed.")
        response.SuccessMessage = retVal;
    else
        response.ErrorMessage = retVal;

    return response;
}

第3。在HTML 中 - 必须从OnClick移除btnChange事件并将ScriptManager控件更改为如此 - <asp:ScriptManager ID="ScriptManagerMain" runat="server" EnableCdn="true" />

<强>输出:

Calling a WebMethod from jQuery using AJAX