UpdatePanel内的标签不会显示代码隐藏分配的值 [英] Label inside UpdatePanel will not show value assigned from code-behind

查看:63
本文介绍了UpdatePanel内的标签不会显示代码隐藏分配的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm at my wits end here. I've defined a user control for a modal that lets users change a password. Inside the modal, the fields are contained in an UpdatePanel, and I'd like to display a success/error message regarding the result of the password change request. However, the Label controls simply will not change.

标记:

<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如下所示:

ScriptManager in the master page looks like this:

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

我尝试了什么:


  • 更改 UpdatePanel 属性。如果我使用 ChildrenAsTriggers =true或手动定义触发器无关紧要。如果我对 UpdateMode 使用Always或Conditional无关紧要。

  • Changing around the UpdatePanel attributes. Doesn't matter if I use ChildrenAsTriggers="true" or define the triggers manually. Doesn't matter if I use "Always" or "Conditional" for the UpdateMode.

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

Calling UpdatePanel1.Update() from the code behind has no effect.

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

Trying to edit the label (or any other element type I put in its place) via a javascript call doesn't work either. Something like ScriptManager.RegisterStartupScript(upnlChangePassword, this.GetType(), "script", string.Format("DisplayProcessingMessage('{0}');", retVal), true); has no effect.

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

I've stepped through the code over and over—all events are firing correctly and the correct values are being returned. I've inspected the DOM before and after the partial postback and the element is always unchanged. There are no javascript errors detected in the browser.

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

This sits in a user control inside a web form that utilizes a master page. In the browser, there is far more in the page than would be useful to post here, so I recognize there could be something outside this file in play. But if I could at least have an idea of what to look for that could cause this behavior, it would be an enormous help.

推荐答案

只需在您的更新面板中添加 PostBackTrigger

Just add a PostBackTrigger to your update panel:

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

OR

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

As a work around, instead of calling a server side click event you could use an AJAX call which posts to a C# [WebMethod].

1.用此替换你的 showProcessingSpinner()函数:

1.Replace your showProcessingSpinner() function with this:

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 :

2.Create a web method in the code behind called ChangePasswordWeb:

[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 中 - 必须从 btnChange 中删除​​ OnClick 事件并更改 ScriptManager 控件看起来像这样 - < asp:ScriptManager ID =ScriptManagerMainrunat =serverEnableCdn =true/>

3. In the HTML - had to remove the OnClick event from btnChange and change the ScriptManager control to look like this - <asp:ScriptManager ID="ScriptManagerMain" runat="server" EnableCdn="true" />

输出:

这篇关于UpdatePanel内的标签不会显示代码隐藏分配的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆