如何在内容页面、asp.net 中使用 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14056777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use javascript in content page, asp.net
提问by Ivan Li
I got a jQuery sample code from tutorial, it's even a single webform sample.
我从教程中得到了一个 jQuery 示例代码,它甚至是一个单一的网络表单示例。
When I integrate it to my project and use it in a content page, the JavaScript doesn't work.
当我将它集成到我的项目中并在内容页面中使用它时,JavaScript 不起作用。
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?
在示例中,所有脚本标签和样式标签都放置在 head 标签内。我应该怎么做才能让它在内容页面的项目中工作?
Edit:
编辑:
Actually this is a jQuery Dialog example which performs basic add, edit and delete functions on data (Customer)
实际上,这是一个 jQuery Dialog 示例,它对数据(客户)执行基本的添加、编辑和删除功能
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.
当前的问题是,当点击链接按钮“btnAddCustomer”时,对话框不显示,可能是javascript没有执行,但是使用RowCommand的gridview中的编辑按钮可以调出对话框。
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();
}
}
}
采纳答案by Lopsided
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...
关于 mandava 的答案,脚本应该在内容页面中正常工作,通过将其保留在那里,您将避免大多数缓存问题。我相信你的问题是...
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:
查看调用 OpenDialog 函数 (btnAddCustomer) 的链接按钮。它是一个asp.net 控件。服务器端 asp.net 控件根据某些变量呈现不同的 ID 值。尝试这个:
- Build the page
- View the source
- Find the rendered code for the asp.net control.
- Use the value of the ID property found in that "view source" code instead.
- 构建页面
- 查看源码
- 找到为 asp.net 控件呈现的代码。
- 请改用在该“查看源代码”代码中找到的 ID 属性的值。
You'll have to this for any asp.net control ID you are using in your javascript code, but I only spotted the one.
对于在 javascript 代码中使用的任何 asp.net 控件 ID,您都必须这样做,但我只发现了一个。
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")
或者更简单的方法是为控件分配一个唯一的类名(例如 Class="myLinkButtonClass"),然后在 jquery 脚本中使用 $(".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
希望有一天我们将有一种通用且简单的方法来引用这些由 ASP 生成的控件 ID,但现在这是您最好的选择。祝你好运
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!
更新:不使用 runat="server" 属性的 DIV 元素应该可以很好地与 jquery/javascript 一起使用。这些 ID 在发送到客户端之前不会被修改。我没有使用 Emmanuel 的 Control.ClientID 建议,但很想知道它是否有效。请让我们知道这是怎么回事!
回答by Emmanuel N
To get dom/html id use Control.ClientID
要获取 dom/html id 使用Control.ClientID
Something like:
就像是:
$("#"+ <%= divEditCustomer.ClientID %>)
回答by Lopsided
I'll add this answer to reiterate...
我将添加此答案以重申...
Once again, I'm pretty absolutely definitely sure this is your issue.
再一次,我非常肯定这是你的问题。
- Try building the page,
- then view source,
- then find the tag for the btnAddCustomer link button,
- then look at the value of the ID property for that button (notice it is different).
- Hi-light this new value and copy it.
- Paste this value into the linkID parameter of the onClientClick function of the btnAddCustomer linkButton.
- 尝试构建页面,
- 然后查看源码
- 然后找到 btnAddCustomer 链接按钮的标签,
- 然后查看该按钮的 ID 属性值(注意它是不同的)。
- 高亮这个新值并复制它。
- 将此值粘贴到 btnAddCustomer linkButton 的 onClientClick 函数的 linkID 参数中。
TADA! You're all set.
多田!你都准备好了。
If it still doesn't work try using the function within the onClick event instead of client click, but the above steps definitely need to be taken or it will not work.
如果它仍然不起作用,请尝试使用 onClick 事件中的函数而不是客户端单击,但上述步骤肯定需要执行,否则将不起作用。
回答by mandava
Hey why dont you write your script in a new js file and add it to the project and include the script reference in the content page / master page . I had faced a similar issue not exactly the same it may work for you. so try it this way it won't take long any way .......
嘿,为什么不在新的 js 文件中编写脚本并将其添加到项目中,并在内容页/母版页中包含脚本引用。我遇到了一个类似的问题,但它可能对你有用。所以试试这种方式它不会花很长时间......
回答by Khalid Hasan
I faced this problem and I searched this for days but in vain
I tested the following:
我遇到了这个问题,我搜索了几天,但徒劳地
我测试了以下内容:
- in content page it is not working
- in master page it is working
- then in content page I replaced the asp button with html button, then it worked
- 在内容页面中它不起作用
- 在母版页它正在工作
- 然后在内容页面中,我用 html 按钮替换了 asp 按钮,然后它起作用了
so the problem is in content page asp button will not hit the script even if you use the reference Id like this
所以问题是内容页面asp按钮不会点击脚本,即使你使用这样的参考ID
$("<%= yourbutton.ClientID%>").click(yourscript)
回答by ArunPratap
when i use it for Content Page i used it like this and it's working for me
当我将它用于内容页面时,我是这样使用的,它对我有用
$("#<%= YourControlID.ClientID %>")

