在 ASP.NET 中使用 jQuery.load() 方法

今天就让我们看看在 ASP.NET 中使用 jQuery.load() 方法来调用 ASP.NET 的方法,实现无刷新的加载数据。

使用 jQuery 的朋友应该知道可以使用 jQuery.load() 加载静态页面,并可指定要加载的区域,如在"test.html"中有如下内容:

<div id="show">
<a href="http://www.jquery001.com/">jQuery001</a>
</div> <div>
<a href="http://www.xxx.com/">xxx</a>
</div>

在调用页面"Default.aspx"如下:

<body>
<div id="result"></div>
</body> $(document).ready(function() {
$("#result").load("test.html #show");
});

相信大家能够想像到输出的结果,这样调用只会加载 id 为"show" 的 div 中的内容。下边我们进入本文的主题,看看在 ASP.NET 中怎么使用 jQuery.load() 方法无刷新的调用后台方法。假如有后台代码如下,它根据 "owner" 参数,绑定rptTest:

public partial class _Default : System.Web.UI.Page
{
public List website;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetTestData(); if (!string.IsNullOrEmpty(Request.QueryString["owner"]))
{
rptTest.DataSource = website.Where(m => m.Owner == Request.QueryString["owner"]);
rptTest.DataBind();
}
}
} public void SetTestData()
{
website = new List();
website.Add(new Website() { Name = "Google+", Owner = "Google" });
website.Add(new Website() { Name = "Youtube", Owner = "Google" });
website.Add(new Website() { Name = "265.com", Owner = "Google" });
website.Add(new Website() { Name = "asp.net", Owner = "Microsoft" });
website.Add(new Website() { Name = "MSN", Owner = "Microsoft" }); } protected void btnTest_Click(object sender, EventArgs e)
{ } } public class Website
{
public string Name { get; set; }
public string Owner { get; set; }
}

前台代码如下,执行 "btnTest" 单击事件时,使用 event.preventDefault()阻止了按钮的默认执行方式,从而使用 jQuery.load() 方法传递了"owner"参数访问 Default.aspx 页面:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#result").load("test.html #show"); $("#<%= btnTest.ClientID %>").click(function(event) {
event.preventDefault();
var owner = $("#<%= ddlTest.ClientID %>").val();
$("#result").load("Default.aspx?owner=" + owner + " #show");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="show">
<asp:Repeater ID="rptTest" runat="server">
<ItemTemplate>
<div><%#Eval("owner") %>:<%#Eval("Name") %></div>
</ItemTemplate>
</asp:Repeater>
</div>
<%=DateTime.Now %>
<div id="result"></div>
<asp:DropDownList ID="ddlTest" runat="server">
<asp:ListItem Value="Google">Google</asp:ListItem>
<asp:ListItem Value="Microsoft">Microsoft</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnTest" runat="server" Text="查询" onclick="btnTest_Click" />
</form>
</body>

其他没有什么新知识,其中输出了当前时间来验证使用这种方法并没有刷新页面,结果如下图所示:

在 ASP.NET 中使用 jQuery.load() 方法在 ASP.NET 中使用 jQuery.load() 方法

在 ASP.NET Webform 中适当使用这种方式可减少页面刷新,从而提高用户体验。你可以从 jQuery学习直接下载在 ASP.NET 中使用 jQuery.load() 方法

http://www.jquery001.com/jquery-load-in-asp-net.html

上一篇:opencv 在工业中的应用:圆孔定位


下一篇:jsp 中登录验证 注销 的模版