使用 jQuery 加载 UserControl





5.00/5 (3投票s)
本文展示了如何使用 jQuery ASPX 页面加载用户控件 <input type="button"
本文展示如何使用 jQuery 加载 usercontrol
ASPX 页面
<div style="float: left; width: 100%;">
<input type="button" id="btnSubmit" value="加载" /></div>
<div id="dvProducts">
</div>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").live("click", function () {
LoadProducts();
$(this).hide();
});
function LoadProducts() {
$.ajax({
type: "POST",
url: "Product.aspx/LoadUserControl",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dvProducts").append(r.d);
}
});
}
});
</script>
用户控件
ucProduct.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ucProduct.ascx.cs" Inherits="jQueryPOC.UserControls.ucProduct" %>
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<div style="float: left; width: 60%;">
<asp:DataList ID="DataList1" runat="server" RepeatColumns="1" RepeatDirection="Horizontal"
DataSourceID="ObjectDataSource1">
<ItemTemplate>
<div>
<asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
<div style="display: none;">
<asp:Label ID="lblProductID" runat="server" Text='<%# Eval("ProductID") %>'></asp:Label>
<asp:ImageMap ID="imgProduct" runat="server" ImageUrl='<%# Eval("ImageName") %>'>
</asp:ImageMap>
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
<div id="dvDetails" style="float: left; width: 20%;display:none; border:1px;">
</div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetProducts"
TypeName="jQueryPOC.UserControls.ucProduct"></asp:ObjectDataSource>
ucProduct.ascx.cs
public IList<ProductDO> GetProducts()
{
IList<ProductDO> products = new List<ProductDO>();
products.Add(new ProductDO { ProductID = 1, ProductName = "Samsung Galaxy S3", Price = 36000, ImageName = "https://:58445/images/SGS3.jpg" });
products.Add(new ProductDO { ProductID = 2, ProductName = "Apple iPhone 4", Price = 35000, ImageName = "https://:58445/images/AiP4.jpg" });
products.Add(new ProductDO { ProductID = 3, ProductName = "Samsung Galaxy Note", Price = 32000, ImageName = "https://:58445/images/SGN.jpg" });
return products;
}
Page 方法获取 UserControl
[WebMethod]
public static string LoadUserControl()
{
using (Page page = new Page())
{
HtmlForm form = new HtmlForm();
UserControl userControl = (UserControl)page.LoadControl("UserControls/ucProduct.ascx");
form.Controls.Add(userControl);
using (StringWriter writer = new StringWriter())
{
page.Controls.Add(form);
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
}
}
但请记住,此 usercontrol 将没有任何 viewstate。因此,如果您在此 UserControl 上有任何按钮,并且您希望在此按钮上执行某些操作,则所有事情都应通过客户端脚本来处理。 在这种情况下,您必须使用 jQuery 或其他客户端库通过 AJAX 提交您的表单。