如何使用JavaScript的内容页面,asp.net [英] How to use javascript in content page, asp.net

查看:172
本文介绍了如何使用JavaScript的内容页面,asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从教程jQuery的样本code,它甚至一个单一的网络表格样本。

当我将它集成到我的项目,并在内容页中使用它时,JavaScript不工作。

这是我的母版页code:

 <%@主语言=C#AutoEventWireup =真codeBehind =Site1.master.cs继承=WebApplication2.Site1%GT;!< D​​OCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
< HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>
<头=服务器>
    <标题>< /标题>
    < ASP:的ContentPlaceHolder ID =头=服务器>
    < / ASP:&的ContentPlaceHolder GT;
< /头>
<身体GT;
    <表ID =form1的=服务器>
    < D​​IV>
        < ASP:的ContentPlaceHolder ID =ContentPlaceHolder1=服务器>
        < / ASP:&的ContentPlaceHolder GT;
    < / DIV>
    < /表及GT;
< /身体GT;
< / HTML>

这是我的内容页code:

 <%@页标题=LANGUAGE =C#的MasterPageFile =〜/ Site1.MasterAutoEventWireup =真
codeBehind =WebForm1.aspx.cs中继承=WebApplication2.WebForm1%GT;
< ASP:内容ID =内容1ContentPlaceHolderID =头=服务器>
< / ASP:内容>
< ASP:内容ID =内容2ContentPlaceHolderID =ContentPlaceHolder1=服务器>
<! - 从http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/ - >
<链接HREF =htt​​p://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/start/jquery-ui.css
    类型=文/ CSS的rel =stylesheet属性/>
<脚本类型=文/ JavaScript的SRC =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =htt​​p://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =<%= RESOLVEURL(〜)%GT;脚本/ jquery.blockUI.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =<%= RESOLVEURL(〜)%GT;脚本/ ScriptFile.js>< / SCRIPT>
<! - 修复在jQuery用户界面1.1em默认字体大小 - >
<风格类型=文/ CSS>
    的.ui小部件
    {
        字体大小:11像素重要;
    }
    的.ui状态错误文本
    {
        保证金左:10px的;
    }
< /风格>
<脚本类型=文/ JavaScript的>
    $(文件)。就绪(函数(){
        $(#divEditCustomer)。对话框({
            的AutoOpen:假的,
            模式:真实,
            了minHeight:20,
            高度:'自动',
            宽度:'自动',
            可调整大小:假的,
            打开:函数(事件,UI){
                $(本).parent()appendTo(#divEditCustomerDlgContainer);
            },
        });
    });
    功能closeDialog(){
        //可能会导致因上接近处理的无限循环
        $(#divEditCustomer)对话框(亲密)。
    }    功能openDialog(标题,的linkID){        变种POS = $(#+的linkID).POSITION();
        VAR顶部= pos.top;
        变种左= pos.left + $(#+的linkID).WIDTH()+ 10;
        $(#divEditCustomer)对话框(选项,标题,标题)。
        $(#divEditCustomer)对话框(选项,位置,[左,上]);        $(#divEditCustomer)对话框(开放)。
    }    功能openDialogAndBlock(标题,的linkID){
        openDialog(标题,的linkID);        //阻止它清理出来的数据
        $(#divEditCustomer)。块({
            消息:'&下; IMG SRC =&下;%= RESOLVEURL(〜)%>内容/图片/ async.gif/>',
            CSS:{边框:0像素},
            淡入:0,
            //淡出:0,
            overlayCSS:{的backgroundColor:'#FFFFFF,不透明度:1}
        });
    }
    功能unblockDialog(){
        $(#divEditCustomer)解除()。
    }    功能onTest(){
        $(#divEditCustomer)。块({
            消息:'< H1>处理< / H1>,
            CSS:{边框:'的3px固体#A00},
            overlayCSS:{的backgroundColor:'#FFFFFF,不透明度:1}
        });
    }
< / SCRIPT>
< ASP:的ScriptManager ID =ScriptManager的=服务器/>
< H1>
    客户与LT; / H1>
< D​​IV ID =divEditCustomerDlgContainer>
    < D​​IV ID =divEditCustomer的风格=显示:无>
        < ASP:的UpdatePanel ID =upnlEditCustomer=服务器>
            <&的ContentTemplate GT;
                < ASP:占位符ID =phrEditCustomer=服务器>
                    <表格的cellpadding =3CELLSPACING =1>
                        &所述; TR>
                            &所述; TD>
                                *名字:
                            < / TD>
                            &所述; TD>
                                < ASP:文本框ID =txtFirstName列=40MAXLENGTH =50=服务器/>
                                < ASP:的RequiredFieldValidator ID =vtxtFirstName=服务器EnableClientScript =假
                                    的CssClass =UI状态错误文本显示=动态的ErrorMessage =必需。的ControlToValidate =txtFirstName/>
                            < / TD>
                        < / TR>
                        &所述; TR>
                            &所述; TD>
                                *姓:
                            < / TD>
                            &所述; TD>
                                < ASP:文本框ID =txtLastName列=40MAXLENGTH =50=服务器/>
                                < ASP:的RequiredFieldValidator ID =vtxtLastName=服务器EnableClientScript =假
                                    的CssClass =UI状态错误文本显示=动态的ErrorMessage =必需。的ControlToValidate =txtLastName/>
                            < / TD>
                        < / TR>
                        &所述; TR>
                            &所述; TD>
                                *电子邮件:
                            < / TD>
                            &所述; TD>
                                < ASP:文本框ID =txtEmail列=40MAXLENGTH =50=服务器/>
                                < ASP:的RequiredFieldValidator ID =vtxtEmail=服务器EnableClientScript =假
                                    的CssClass =UI状态错误文本显示=动态的ErrorMessage =必需。的ControlToValidate =txtEmail/>
                                < ASP:RegularEx pressionValidator ID =vtxtEmail2=服务器EnableClientScript =假
                                    的CssClass =UI状态错误文本的ControlToValidate =txtEmailValidationEx pression =* @ * \\ .. *
                                    的ErrorMessage =不是一个有效的电子邮件。显示=动态/>
                            < / TD>
                        < / TR>
                        &所述; TR>
                            &所述; TD>
                                电话:
                            < / TD>
                            &所述; TD>
                                < ASP:文本框ID =txtPhone列=20MAXLENGTH =20=服务器/>
                            < / TD>
                        < / TR>
                        &所述; TR>
                            &所述; TD>
                                出生日期:
                            < / TD>
                            &所述; TD>
                                < ASP:文本框ID =txtDateOfBirth列=10MAXLENGTH =20=服务器/>
                                < ASP:CompareValidator ID =vtxtDateOfBirth=服务器EnableClientScript =假
                                    的CssClass =UI状态错误文本的ControlToValidate =txtDateOfBirth的ErrorMessage =不是一个有效的日期。
                                    操作=DataTypeCheck类型=日期/>
                            < / TD>
                        < / TR>
                        &所述; TR>
                            < TD合并单元格=2ALIGN =右>
                                < ASP:按钮的ID =btnSave的OnClick =btnSave_Click文本=保存=服务器/>
                                < ASP:按钮的ID =btnCancel的OnClick =btnCancel_Click的OnClientClick =closeDialog()
                                    的CausesValidation =false的文本=取消=服务器/>
                            < / TD>
                        < / TR>
                    < /表>
                < / ASP:占位符>
            < /&的ContentTemplate GT;
        < / ASP:的UpdatePanel>
    < / DIV>
< / DIV>
&所述;! - divEditCustomerDlgContainer - >
<! -
    < BR />< BR />
    <输入类型=按钮ID =为btnTest的onclick =onTestVALUE =测试/>
    < BR />< BR />
     - >
< ASP:的UpdatePanel ID =upnlCustomers的UpdateMode =条件=服务器>
    <&的ContentTemplate GT;
        < ASP:LinkBut​​ton的ID =btnAddCustomer文本=添加用户=服务器的OnClientClick =openDialogAndBlock(添加用户,btnAddCustomer')
            的CausesValidation =假的OnClick =btnAddCustomer_Click>< / ASP:LinkBut​​ton的>
        < BR />
        < BR />
        < ASP:GridView控件ID =gvCustomers=服务器的AutoGenerateColumns =FALSE的cellpadding =4
            CELLSPACING =1OnRowDataBound =gvCustomer_RowDataBoundOnRowCommand =gvCustomers_RowCommand>
            <柱体和GT;
                < ASP:的TemplateField的HeaderText =名称>
                    <&ItemTemplate中GT;
                        <%#的eval(名字)++的eval(姓氏)%>
                    < / ItemTemplate中>
                < / ASP:的TemplateField>
                < ASP:BoundField的数据字段=手机的HeaderText =电话/>
                < ASP:BoundField的数据字段=电子邮件的HeaderText =电子邮件/>
                < ASP:BoundField的数据字段=DATEOFBIRTH的HeaderText =出生日期DataFormatString ={0:MMMM D,YYYY}/>
                < ASP:的TemplateField的HeaderText =操作>
                    <&ItemTemplate中GT;
                        < ASP:LinkBut​​ton的ID =btnEdit文本=编辑的CommandName =EditCustomer的CausesValidation =假
                            CommandArgument ='<%#的eval(ID)%GT;' =服务器>< / ASP:LinkBut​​ton的>
                        < ASP:LinkBut​​ton的ID =btnDelete文本=删除的CommandName =DeleteCustomer的CausesValidation =假
                            CommandArgument ='<%#的eval(ID)%GT;' =服务器>< / ASP:LinkBut​​ton的>
                    < / ItemTemplate中>
                < / ASP:的TemplateField>
            < /专栏>
        < / ASP:GridView的>
        < ASP:LinkBut​​ton的ID =btnRefreshGrid的CausesValidation =假的OnClick =btnRefreshGrid_Click
            风格=显示:无=服务器>< / ASP:LinkBut​​ton的>
    < /&的ContentTemplate GT;
< / ASP:的UpdatePanel>
< ASP:的UpdatePanel ID =upnlJsRunner的UpdateMode =始终=服务器>
    <&的ContentTemplate GT;
        < ASP:占位符ID =phrJsRunner=服务器>< / ASP:占位符>
    < /&的ContentTemplate GT;
< / ASP:的UpdatePanel>
<脚本类型=文/ JavaScript的SRC =内容/脚本/ ScriptFile.js>
< / SCRIPT>

在样品中,所有的脚本标签和样式标签放置在头部标记内。
我应该怎么做才能得到它在我的项目工作,在内容页?


编辑:

其实,这是一个jQuery对话框例子进行基本的添加,编辑和删除功能的数据(客户)

目前的问题是,当点击链接按钮btnAddCustomer时,对话框不显示,它可能是JavaScript并不是然而,在GridView中使用RowCommand可以弹出对话框中执行,编辑按钮。

要更好地阐明我的问题,这里是code背后:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.UI程序;
使用System.Web.UI.WebControls;命名空间WebApplication2
{
    公共部分类WebForm1的:System.Web.UI.Page
    {
        私人的CustomerService _customerService;        #区域属性
        私人布尔IsAdd
        {
            得到
            {
                回报(!EditCustomerID.HasValue);
            }
        }        私人诠释? EditCustomerID
        {
            得到
            {
                返程(INT?)的ViewState [EditCustomerID];
            }            组
            {
                的ViewState [EditCustomerID] =值;
            }
        }        #endregion
    保护无效的Page_Load(对象发件人,EventArgs的发送)
    {
        _customerService =新的CustomerService();        如果(!的IsPostBack)
        {
            GridDataBind();
        }
    }
    私人无效GridDataBind()
    {
        gvCustomers.DataSource = _customerService.GetAll();
        gvCustomers.DataBind();
    }
    保护无效btnAddCustomer_Click(对象发件人,EventArgs的发送)
    {
        this.EditCustomerID = NULL;        ClearEditCustomerForm(); //如果使用非模态        的RegisterStartupScript(jsUnblockDialog,unblockDialog(););
    }
    私人无效ClearEditCustomerForm()
    {
        //空出的文本框
        VAR文本框=新的List<控制>();
        FindControlsOfType(this.phrEditCustomer的typeof(文本框),文本框);        的foreach(在文本框文本框textBox中)
            textBox.Text =;        //清除验证
        VAR验证=新的List<控制>();
        FindControlsOfType(this.phrEditCustomer的typeof(BaseValidator),验证);        的foreach(在验证BaseValidator验证)
            validator.IsValid = TRUE;
    }
    静态公共无效FindControlsOfType(控制根,类型controlType,列表与LT;控制>名单)
    {
        如果(root.GetType()== controlType || root.GetType()。IsSubclassOf(controlType))
        {
            list.Add(根);
        }        //跳过输入控件
        如果(!root.HasControls())
            返回;        的foreach(在root.Controls控制控制)
        {
            FindControlsOfType(控制,controlType,清单);
        }
    }
    保护无效gvCustomer_RowDataBound(对象发件人,GridViewRowEventArgs E)
    {
        如果(e.Row.DataItem == NULL)
            返回;        变种btnEdit =(LinkBut​​ton的)e.Row.FindControl(btnEdit);
        btnEdit.OnClientClick =openDialogAndBlock(编辑客户,+ btnEdit.ClientID +');
    }
    保护无效gvCustomers_RowCommand(对象发件人,GridViewCommandEventArgs E)
    {
        INT的customerID = Convert.ToInt32(e.CommandArgument);        开关(e.CommandName)
        {
            //不能只使用编辑和删除或需要绕过RowEditing和删除
            案EditCustomer:
                客户客户= _customerService.GetByID(的customerID);
                FillEditCustomerForm(客户);                this.EditCustomerID =的customerID;
                的RegisterStartupScript(jsUnblockDialog,unblockDialog(););                //设置定时器来测试更长的加载
                //Thread.Sleep(2000);
                打破;            案DeleteCustomer:
                _customerService.Delete(的customerID);                GridDataBind();
                打破;
        }
    }    私人无效FillEditCustomerForm(客户的客户)
    {
        txtFirstName.Text = customer.FirstName;
        txtLastName.Text = customer.LastName;
        txtEmail.Text = customer.Email;
        txtPhone.Text = customer.Phone;
        txtDateOfBirth.Text = customer.DateOfBirth.HasValue? customer.DateOfBirth.Value.ToShortDateString():;
    }
    私人无效TriggerClientGridRefresh()
    {
        串脚本=__doPostBack(\\+ btnRefreshGrid.ClientID +\\\\\\);;
        的RegisterStartupScript(jsGridRefresh脚本);
    }
    私人无效的RegisterStartupScript(字符串键,字符串脚本)
    {
        ScriptManager.RegisterStartupScript(phrJsRunner,phrJsRunner.GetType()键,脚本,真正的);
    }    保护无效btnSave_Click(对象发件人,EventArgs的发送)
    {
        如果(!Page.IsValid)
            返回;        客户的客户;        如果(this.IsAdd)
            客户=新客户();
        其他
            客户= _customerService.GetByID(this.EditCustomerID.Value);        customer.FirstName = txtFirstName.Text;
        customer.LastName = txtLastName.Text;
        customer.Email = txtEmail.Text;
        customer.Phone = txtPhone.Text;        如果(!String.IsNullOrEmpty(txtDateOfBirth.Text))
            customer.DateOfBirth = DateTime.Parse(txtDateOfBirth.Text);        如果(this.IsAdd)
            _customerService.Add(客户);
        其他
            _customerService.Update(客户);        HideEditCustomer();        TriggerClientGridRefresh();
    }
    私人无效HideEditCustomer()
    {
        ClearEditCustomerForm();        的RegisterStartupScript(jsCloseDialg,closeDialog(););
    }
    保护无效btnCancel_Click(对象发件人,EventArgs的发送)
    {
        HideEditCustomer();
    }
    保护无效btnRefreshGrid_Click(对象发件人,EventArgs的发送)
    {
        GridDataBind();
    }
}
}


解决方案

关于mandava的回答,该脚本应该工作内容页面中,并保持它在那里你会避免大部分缓存问题就好了。我相信你的问题是这样的...

看看你的链接按钮调用OpenDialog功能(btnAddCustomer)。它是一个asp.net控制。服务器端asp.net控件呈现基于某些变量不同的ID值。试试这个:


  1. 构建页面

  2. 查看源代码

  3. 找到所呈现的code的asp.net控制。

  4. 使用在查看源文件code,而不是找到ID属性的值。

您得这个你正在使用你的JavaScript code任何asp.net控件的ID,但我只发现了一个。

或者更简单的方法将是一个独特的类名分配给控件(例如,类=myLinkBut​​tonClass),只是引用了jQuery脚本使用$(。myLinkBut​​tonClass)

希望有一天我们将不得不引用这些ASP生成控件ID普遍和简单的方法,但现在这是你最好的选择。祝你好运

更新:不使用runat =服务器属性的div元素应该只是使用jQuery / JavaScript的罚款。的ID不被发送到客户端之前修改。我没有使用过灵光的Control.ClientID建议,但我非常有兴趣知道,如果它的工作原理。请让我们知道如何继续下去!

I got a jQuery sample code from tutorial, it's even a single webform sample.

When I integrate it to my project and use it in a content page, the JavaScript doesn't work.

This is my master page code:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApplication2.Site1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

this is my content page code:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<!-- from http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/ -->
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/start/jquery-ui.css"
    type="text/css" rel="Stylesheet" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~")%>Scripts/jquery.blockUI.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/ScriptFile.js"></script>
<!-- fix for 1.1em default font size in Jquery UI -->
<style type="text/css">
    .ui-widget
    {
        font-size: 11px !important;
    }
    .ui-state-error-text
    {
        margin-left: 10px;
    }
</style>
<script type="text/javascript">
    $(document).ready(function() {
        $("#divEditCustomer").dialog({
            autoOpen: false,
            modal: true,
            minHeight: 20,
            height: 'auto',
            width: 'auto',
            resizable: false,
            open: function(event, ui) {
                $(this).parent().appendTo("#divEditCustomerDlgContainer");
            },
        });
    });


    function closeDialog() {
        //Could cause an infinite loop because of "on close handling"
        $("#divEditCustomer").dialog('close');
    }

    function openDialog(title, linkID) {

        var pos = $("#" + linkID).position();
        var top = pos.top;
        var left = pos.left + $("#" + linkID).width() + 10;


        $("#divEditCustomer").dialog("option", "title", title);
        $("#divEditCustomer").dialog("option", "position", [left, top]);

        $("#divEditCustomer").dialog('open');
    }



    function openDialogAndBlock(title, linkID) {
        openDialog(title, linkID);

        //block it to clean out the data
        $("#divEditCustomer").block({
            message: '<img src="<%=ResolveUrl("~") %>content/images/async.gif" />',
            css: { border: '0px' },
            fadeIn: 0,
            //fadeOut: 0,
            overlayCSS: { backgroundColor: '#ffffff', opacity: 1 } 
        });
    }


    function unblockDialog() {
        $("#divEditCustomer").unblock();
    }

    function onTest() {
        $("#divEditCustomer").block({
            message: '<h1>Processing</h1>',
            css: { border: '3px solid #a00' },
            overlayCSS: { backgroundColor: '#ffffff', opacity: 1 } 
        });
    }
</script>
<asp:ScriptManager ID="scriptManager" runat="server" />
<h1>
    Customers</h1>
<div id="divEditCustomerDlgContainer">
    <div id="divEditCustomer" style="display: none">
        <asp:UpdatePanel ID="upnlEditCustomer" runat="server">
            <ContentTemplate>
                <asp:PlaceHolder ID="phrEditCustomer" runat="server">
                    <table cellpadding="3" cellspacing="1">
                        <tr>
                            <td>
                                *First Name:
                            </td>
                            <td>
                                <asp:TextBox ID="txtFirstName" Columns="40" MaxLength="50" runat="server" />
                                <asp:RequiredFieldValidator ID="vtxtFirstName" runat="server" EnableClientScript="false"
                                    CssClass="ui-state-error-text" Display="Dynamic" ErrorMessage="Required." ControlToValidate="txtFirstName" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                *Last Name:
                            </td>
                            <td>
                                <asp:TextBox ID="txtLastName" Columns="40" MaxLength="50" runat="server" />
                                <asp:RequiredFieldValidator ID="vtxtLastName" runat="server" EnableClientScript="false"
                                    CssClass="ui-state-error-text" Display="Dynamic" ErrorMessage="Required." ControlToValidate="txtLastName" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                *Email:
                            </td>
                            <td>
                                <asp:TextBox ID="txtEmail" Columns="40" MaxLength="50" runat="server" />
                                <asp:RequiredFieldValidator ID="vtxtEmail" runat="server" EnableClientScript="false"
                                    CssClass="ui-state-error-text" Display="Dynamic" ErrorMessage="Required." ControlToValidate="txtEmail" />
                                <asp:RegularExpressionValidator ID="vtxtEmail2" runat="server" EnableClientScript="false"
                                    CssClass="ui-state-error-text" ControlToValidate="txtEmail" ValidationExpression=".*@.*\..*"
                                    ErrorMessage="Not a valid email." Display="Dynamic" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                Phone:
                            </td>
                            <td>
                                <asp:TextBox ID="txtPhone" Columns="20" MaxLength="20" runat="server" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                Date of Birth:
                            </td>
                            <td>
                                <asp:TextBox ID="txtDateOfBirth" Columns="10" MaxLength="20" runat="server" />
                                <asp:CompareValidator ID="vtxtDateOfBirth" runat="server" EnableClientScript="false"
                                    CssClass="ui-state-error-text" ControlToValidate="txtDateOfBirth" ErrorMessage="Not a valid date."
                                    Operator="DataTypeCheck" Type="Date" />
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" align="right">
                                <asp:Button ID="btnSave" OnClick="btnSave_Click" Text="Save" runat="server" />
                                <asp:Button ID="btnCancel" OnClick="btnCancel_Click" OnClientClick="closeDialog()"
                                    CausesValidation="false" Text="Cancel" runat="server" />
                            </td>
                        </tr>
                    </table>
                </asp:PlaceHolder>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
</div>
<!-- divEditCustomerDlgContainer -->
<!--
    <br /><br />
    <input type="button" id="btnTest" onclick="onTest" value="Test" />
    <br /><br />
    -->
<asp:UpdatePanel ID="upnlCustomers" UpdateMode="Conditional" runat="server">
    <ContentTemplate>
        <asp:LinkButton ID="btnAddCustomer" Text="Add Customer" runat="server" OnClientClick="openDialogAndBlock('Add Customer', 'btnAddCustomer')"
            CausesValidation="false" OnClick="btnAddCustomer_Click"></asp:LinkButton>
        <br />
        <br />
        <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False" CellPadding="4"
            CellSpacing="1" OnRowDataBound="gvCustomer_RowDataBound" OnRowCommand="gvCustomers_RowCommand">
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%# Eval("FirstName") + " " + Eval("LastName")%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Phone" HeaderText="Phone" />
                <asp:BoundField DataField="Email" HeaderText="Email" />
                <asp:BoundField DataField="DateOfBirth" HeaderText="Date Of Birth" DataFormatString="{0:MMMM d, yyyy}" />
                <asp:TemplateField HeaderText="Actions">
                    <ItemTemplate>
                        <asp:LinkButton ID="btnEdit" Text="Edit" CommandName="EditCustomer" CausesValidation="false"
                            CommandArgument='<%#Eval("ID")%>' runat="server"></asp:LinkButton>
                        <asp:LinkButton ID="btnDelete" Text="Delete" CommandName="DeleteCustomer" CausesValidation="false"
                            CommandArgument='<%#Eval("ID")%>' runat="server"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:LinkButton ID="btnRefreshGrid" CausesValidation="false" OnClick="btnRefreshGrid_Click"
            Style="display: none" runat="server"></asp:LinkButton>
    </ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="upnlJsRunner" UpdateMode="Always" runat="server">
    <ContentTemplate>
        <asp:PlaceHolder ID="phrJsRunner" runat="server"></asp:PlaceHolder>
    </ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript" src="Content/scripts/ScriptFile.js">
</script>

In the sample, all script tags and style tags are placed inside the head tag. what should I do to get it to work in my project in the content page?


Edit:

Actually this is a jQuery Dialog example which performs basic add, edit and delete functions on data (Customer)

Current problem is, when the link button "btnAddCustomer" is clicked, dialog box doesn't show, it's probably the javascript is not executing, however, the edit button in gridview using RowCommand can bring up the dialog box.

to better clarify my question, here is the code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private CustomerService _customerService;

        #region Properties
        private bool IsAdd
        {
            get
            {
                return (!EditCustomerID.HasValue);
            }
        }

        private int? EditCustomerID
        {
            get
            {
                return (int?)ViewState["EditCustomerID"];
            }

            set
            {
                ViewState["EditCustomerID"] = value;
            }
        }

        #endregion


    protected void Page_Load(object sender, EventArgs e)
    {
        _customerService = new CustomerService();

        if (!IsPostBack)
        {
            GridDataBind();
        }
    }


    private void GridDataBind()
    {
        gvCustomers.DataSource = _customerService.GetAll();
        gvCustomers.DataBind();
    }


    protected void btnAddCustomer_Click(object sender, EventArgs e)
    {
        this.EditCustomerID = null;

        ClearEditCustomerForm();    //In case using non-modal

        RegisterStartupScript("jsUnblockDialog", "unblockDialog();");
    }


    private void ClearEditCustomerForm()
    {
        //Empty out text boxes
        var textBoxes = new List<Control>();
        FindControlsOfType(this.phrEditCustomer, typeof(TextBox), textBoxes);

        foreach (TextBox textBox in textBoxes)
            textBox.Text = "";

        //Clear validators
        var validators = new List<Control>();
        FindControlsOfType(this.phrEditCustomer, typeof(BaseValidator), validators);

        foreach (BaseValidator validator in validators)
            validator.IsValid = true;
    }


    static public void FindControlsOfType(Control root, Type controlType, List<Control> list)
    {
        if (root.GetType() == controlType || root.GetType().IsSubclassOf(controlType))
        {
            list.Add(root);
        }

        //Skip input controls
        if (!root.HasControls())
            return;

        foreach (Control control in root.Controls)
        {
            FindControlsOfType(control, controlType, list);
        }
    }


    protected void gvCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem == null)
            return;

        var btnEdit = (LinkButton)e.Row.FindControl("btnEdit");
        btnEdit.OnClientClick = "openDialogAndBlock('Edit Customer', '" + btnEdit.ClientID + "')";
    }


    protected void gvCustomers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int customerID = Convert.ToInt32(e.CommandArgument);

        switch (e.CommandName)
        {
            //Can't use just Edit and Delete or need to bypass RowEditing and Deleting
            case "EditCustomer":
                Customer customer = _customerService.GetByID(customerID);
                FillEditCustomerForm(customer);

                this.EditCustomerID = customerID;
                RegisterStartupScript("jsUnblockDialog", "unblockDialog();");

                //Setting timer to test longer loading
                //Thread.Sleep(2000);
                break;

            case "DeleteCustomer":
                _customerService.Delete(customerID);

                GridDataBind();
                break;
        }
    }

    private void FillEditCustomerForm(Customer customer)
    {
        txtFirstName.Text = customer.FirstName;
        txtLastName.Text = customer.LastName;
        txtEmail.Text = customer.Email;
        txtPhone.Text = customer.Phone;
        txtDateOfBirth.Text = customer.DateOfBirth.HasValue ? customer.DateOfBirth.Value.ToShortDateString() : "";
    }


    private void TriggerClientGridRefresh()
    {
        string script = "__doPostBack(\"" + btnRefreshGrid.ClientID + "\", \"\");";
        RegisterStartupScript("jsGridRefresh", script);
    }


    private void RegisterStartupScript(string key, string script)
    {
        ScriptManager.RegisterStartupScript(phrJsRunner, phrJsRunner.GetType(), key, script, true);
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        Customer customer;

        if (this.IsAdd)
            customer = new Customer();
        else
            customer = _customerService.GetByID(this.EditCustomerID.Value);

        customer.FirstName = txtFirstName.Text;
        customer.LastName = txtLastName.Text;
        customer.Email = txtEmail.Text;
        customer.Phone = txtPhone.Text;

        if (!String.IsNullOrEmpty(txtDateOfBirth.Text))
            customer.DateOfBirth = DateTime.Parse(txtDateOfBirth.Text);

        if (this.IsAdd)
            _customerService.Add(customer);
        else
            _customerService.Update(customer);

        HideEditCustomer();

        TriggerClientGridRefresh();
    }


    private void HideEditCustomer()
    {
        ClearEditCustomerForm();

        RegisterStartupScript("jsCloseDialg", "closeDialog();");
    }


    protected void btnCancel_Click(object sender, EventArgs e)
    {
        HideEditCustomer();
    }


    protected void btnRefreshGrid_Click(object sender, EventArgs e)
    {
        GridDataBind();
    }
}
}

解决方案

Regarding mandava's answer, the script should work just fine within the content page and by keeping it there you will avoid most caching issues. I believe your problem is this...

Look at your link button that calls the OpenDialog function (btnAddCustomer). It is an asp.net control. Server-side asp.net controls are rendered a different ID value based on certain variables. Try this:

  1. Build the page
  2. View the source
  3. Find the rendered code for the asp.net control.
  4. Use the value of the ID property found in that "view source" code instead.

You'll have to this for any asp.net control ID you are using in your javascript code, but I only spotted the one.

Or an even easier way would be to assign a unique class name to the control (e.g., Class="myLinkButtonClass") and just reference that in the jquery script using $(".myLinkButtonClass")

Hopefully one day we'll have a universal and easy way to reference these asp-generated control IDs but for now this is your best bet. Good luck

Update: DIV elements that do not use the runat="server" property should work just fine with jquery/javascript. The IDs are not modified before being sent to the client. I haven't used Emmanuel's Control.ClientID suggestion, but am very interested to know if it works. Please let us know how that goes!

这篇关于如何使用JavaScript的内容页面,asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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