如何输出用户控件

在编写ajax程序展示表格数据时候,很多的时候我们直接是用UpdatePanel,这样最快速,但是对微软的的ajax熟悉的人都知道,ms的ajax
框架是非常臃肿的(在你执行异步提交的时候,其实还是把整个页面全部发回服务器)
放弃UpdatePanel,使用请求web服务返回json数据从性能上考虑确实传输量是最小的,但是这里的开发效率有非常的慢(即使使用jquery-jtemplates)

在这里我们考虑一种折中的方案:在服务器端返回拼接好的html,在客户端直接赋值给一个div.那么如何在服务器端高效快速的拼接一个table呢?
答案就是使用用户控件!

新建一个用户控件,里边放一个数据展示控件,在Page_Load里边写好绑定函数

.ascx

<div class="customers">

    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
       
            <div>   
                <a href="javascript:CustomerService.GetOrdersByCustomer('<%# Eval("CustomerID") %>', displayOrders)">
                    <%# Eval("CompanyName") %>
                </a>
            </div>

        </ItemTemplate>
    </asp:Repeater>

</div>


   

.cs

    protected void Page_Load(object sender, EventArgs e)
    {       
        Repeater1.DataBind();
    }
   
    #region IDataSource 成员

    public object DataSource //在这里实现一个接口,不要把筛选逻辑放在这里(怎么看都像mvc)
    {
        get
        {
            return this.Repeater1.DataSource;
        }
        set
        {
            this.Repeater1.DataSource = value;
        }
    }

    #endregion

 如何调用呢

public class ViewManager
{
    public static string RenderView(string path)
    {
        return RenderView(path, null);
    }

    public static string RenderView(string path, object data)
    {
        Page pageHolder = new Page();
        UserControl viewControl = (UserControl)pageHolder.LoadControl(path);
        if (viewControl is IDataSource)
        {
            (viewControl as IDataSource).DataSource = data;
        }


        pageHolder.Controls.Add(viewControl);

        StringWriter output = new StringWriter();
        HttpContext.Current.Server.Execute(pageHolder, output, false);
        return output.ToString();//这里就是拼接好的html标签
    }
}

把这个东西放在web服务中返回字符串就可以了

    [WebMethod]
    public string GetCustomersByCountry(string country)
    {
        NorthwindTableAdapters.CustomersTableAdapter customersAdapter = new NorthwindTableAdapters.CustomersTableAdapter();
        Northwind.CustomersDataTable customers = customersAdapter.GetCustomersByCountry(country);

        if (customers.Rows.Count > 0)
            return ViewManager.RenderView("~/App_Views/Customers.ascx", customers);
        else
            return ViewManager.RenderView("~/App_Views/NoCustomers.ascx", null);
    }

posted on 2009-05-06 16:45  啊啦星  阅读(229)  评论(0编辑  收藏  举报