2012-12-27 49 views
1

我從教程中獲得了一個jQuery示例代碼,它甚至是一個單獨的webform示例。如何在內容頁面使用javascript,asp.net

當我將它集成到我的項目並在內容頁面中使用它時,JavaScript不起作用。

這是我的母版頁代碼:

<%@ 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> 

這是我的內容頁面代碼:

<%@ 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> 

在樣品中,所有的腳本標籤和風格標籤置於其內頭標籤。 我應該怎麼做才能讓它在我的項目中的內容頁面中工作?


編輯:

實際上這是一個jQuery對話框示例,其執行基本的添加,編輯和刪除功能的數據(客戶)

目前的問題是,當鏈接按鈕「btnAddCustomer」是點擊,對話框不顯示,它可能是JavaScript沒有執行,但是,GridView中使用RowCommand的編輯按鈕可以調出對話框。

更好地闡明我的問題,這裏是後面的代碼:

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(); 
    } 
} 
} 
+0

你會得到什麼錯誤?你有沒有試過用控制檯調試? – sinanakyazici

+2

我沒有任何直接的錯誤或衝突,但它看起來像你混合的JavaScript與UpdatePanels,這總是有點過分。你應該使用螢火蟲或鉻的JavaScript控制檯來幫助調試任何可能引發的JavaScript錯誤。 –

+0

要從樣本中獲取所有腳本標籤和樣式標籤,並將其放在頭標籤中,請嘗試將它們放在內容頁面上ID爲_Content1_的元素中。如果這將解決主要問題是另一個問題。 – HenrikW

回答

2

關於mandava的答案,腳本應該在內容頁面中工作得很好,並保持在那裏,您將避免大多數緩存問題。我相信你的問題是這樣的...

看看你的鏈接按鈕,調用OpenDialog函數(btnAddCustomer)。這是一個asp.net控件。服務器端的asp.net控件根據某些變量呈現不同的ID值。試試這個:

  1. 構建頁面
  2. 查看源
  3. 查找的asp.net控制渲染代碼。
  4. 改爲使用在該「查看源代碼」中找到的ID屬性的值。

對於您在JavaScript代碼中使用的任何asp.net控件ID,您將必須使用該控件,但我只發現了它。

或者更簡單的方法將是一個獨特的類名分配給控件(如類=「myLinkBut​​tonClass」)和剛纔提到的是,在jQuery腳本使用$(「 myLinkBut​​tonClass」)

希望有一天,我們將有一個通用和簡單的方法來引用這些asp生成的控制ID,但現在這是你最好的選擇。祝你好運

更新:不使用runat =「server」屬性的DIV元素應該適用於jquery/javascript。在發送給客戶端之前,ID不會被修改。我沒有使用Emmanuel的Control.ClientID建議,但我很感興趣知道它是否有效。請讓我們知道那是怎麼回事!

+0

謝謝隊友,它完美的工作後,我修復了它的客戶端ID的按鈕ID。 –

1

嘿你爲什麼不寫你的腳本在一個新的js文件,並將其添加到項目中,包括在內容頁面的腳本引用/母版頁。我遇到了一個類似的問題,它可能不適合你。所以嘗試這種方式不會花費很長的時間.......

2

要獲得DOM/HTML的id使用Control.ClientID

喜歡的東西:

$("#"+ <%= divEditCustomer.ClientID %>) 
2

我會添加這個答案重申...

再次,我敢肯定絕對確定這是你的問題。

  1. 嘗試建立頁面,
  2. 然後查看源,
  3. 然後找到了btnAddCustomer鏈接按鈕標籤,
  4. 再看看ID屬性的值該按鈕(注意它是不同)。
  5. 嗨,點亮這個新的價值,並複製它。
  6. 將此值粘貼到btnAddCustomer linkBut​​ton的onClientClick 函數的linkID參數中。

TADA!你一切都準備好了。

如果仍然無法正常工作,請嘗試在onClick事件中使用該功能,而不是客戶端點擊,但上述步驟肯定需要進行或無法使用。

0

我面對這個問題,我搜索這幾天卻徒勞無功
我測試了以下:

    在內容頁
  • 它不工作在母版頁
  • 它正在
  • 然後在內容頁我更換了ASP的按鈕,HTML按鈕,然後它的工作

所以這個問題是在內容頁ASP但噸即使你使用這樣的參考ID也不會碰到腳本

$("<%= yourbutton.ClientID%>").click(yourscript) 
+0

格式化您的答案:-) –

相關問題