动态的呈现页面. 模拟ASP.NET UpdatePanel部分更新配合WebServices.

在平常工作中,我们经常遇到需要将页面GridView导出到EXCEL, 通常做法我们就是动态构建以个Page及Form,然后写到返回流(Response)中.
using  System;
using  System.Web;
using  System.Web.UI;
using  System.IO;
using  System.Reflection;
using  System.Web.UI.HtmlControls;

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);
        HtmlForm hf 
=   new  HtmlForm();
        hf.Attributes.Add(
" runat " " server " );
       
        
if  (data  !=   null )
        {
            Type viewControlType 
=  viewControl.GetType();            
            FieldInfo field 
=  viewControlType.GetField( " Data " );

            
if  (field  !=   null )
            {
                field.SetValue(viewControl, data);
            }
            
else
            {
                
throw   new  Exception( " View file:  "   +  path  +   "  does not have a public Data property " );
            }
        }
        hf.Controls.Add(viewControl);
        pageHolder.Controls.Add(hf);

        StringWriter output 
=   new  StringWriter();
        HttpContext.Current.Server.Execute(pageHolder, output, 
false );

        
return  output.ToString();
    }
}

//
protected   void  Button1_Click( object  sender, EventArgs e)
    {
        List
< string >  obj  =   new  List < string > ();
        
for  ( int  i  =   0 ; i  <   10 ; i ++ )
            obj.Add(i.ToString());
        
string  str  =  ViewManager.RenderView( " UserControls/User.ascx " , obj);
        Response.Write(str);
    }
More: http://blog.joycode.com/scottgu/archive/2006/10.aspx

你可能感兴趣的:(WebServices)