繁体   English   中英

未从ASP.NET用户控件调用Javascript

[英]Javascript is not being called from ASP.NET User Control

我将ASP.NET页面DeleteUser.aspx转换为用户控件DeleteUser.ascx

aspx页面有一个简单的javascript函数,如下所示:

function deleteConfirmation() {

    var xusername = document.getElementById('<%= txtusercn.ClientID %>').value;
    if (xusername != null && xusername != "") {
        var userTextBoxId = '<%= txtusercn.ClientID %>';
        var uname = document.getElementById(userTextBoxId).value;
        return confirm('Are you sure you want to delete \'' + uname + '\'?');
    }
    else {
        alert('Please enter Usercn');
        return false
    }
}

现在,因为它被转换为用户控件DeleteUser.ascx ,我首先将此javascript代码移动到<head>标记中包含的aspx文件中。 页面抛出异常txtusercn不在包含aspx文件的范围内。

然后我将javascript函数移动到一个单独的javascript文件DeleteUser.js中,并从DeleteUser.ascx.cs引用它,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterClientScriptInclude(typeof(DeleteUser),"DeleteUserScript",@"../scripts/DeleteUser.js");
}

这里没有调用javascript函数,但是当我检查包含aspx文件的页面源时,我可以看到javascript函数已正确注册。

为什么即使在页面引用javascript文件DeleteUser.js之后也没有调用javascript函数


编辑:

调用这样的函数:

<asp:Button ID="btndeleteusercn" runat="server" Text="Delete Usercn" OnClick="btndeleteusercn_Click" OnClientClick="return deleteConfirmation();" />

我猜,“<%= txtusercn.ClientID%>”必须创建JavaScript错误,因为此类服务器控件引用应位于存在相关控件的页面上。 您应该通过参数将ControlID传递给函数,然后它应该工作。

function deleteConfirmation(ctrlID) {

var xusername = document.getElementById(ctrlID).value;
if (xusername != null && xusername != "") {
    var userTextBoxId = ctrlID;
    var uname = document.getElementById(userTextBoxId).value;
    return confirm('Are you sure you want to delete \'' + uname + '\'?');
}
else {
    alert('Please enter Usercn');
    return false
}}

并通过从那里传递ID来调用Method。

deleteConfirmation('控件ID')

请尝试此更新的代码。

function deleteConfirmation() {

        var xusername = document.getElementById('<%= txtusercn.ClientID %>').value;
        if (xusername != null && xusername != "") {
            return confirm('Are you sure you want to delete \'' + xusername + '\'?');
        }
        else {
            alert('Please enter Usercn');
            return false
        }
return true;

    }

文本框的客户端ID呈现为DeleteUser1_txtusercn ,因此我更改了这样的javascript并且它工作正常:

function deleteConfirmation() {

    var uname = document.getElementById('DeleteUser1_txtusercn').value;
    if (uname != null && uname != "") {
        return confirm('Are you sure you want to delete \'' + uname + '\'?');
    }
    else {
        alert('Please enter UserCN');
        return false;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM