我创建了一个页面来在更新面板中显示多个用户控件.某些用户控件的加载速度会更快,而某些控件可能需要更长的时间才能加载.现在,当页面加载时,它等待所有用户控件加载并仅在此之后显示页面.但是我希望用每个加载器图像异步加载用户控件,以便轻量级用户控件可以轻松加载而无需等待较重的用户控件.
请帮我找一个解决方案.
我已使用上述方法成功将用户控件加载到我的页面中.但是现在我在加载包含标签容器,日历扩展器等ajax控件的usercontrol时遇到了困难.
解决方法
您将遇到一系列问题:ViewState,需要表单标签的控件,回发将无法工作,但如果您使用纯粹是View的控件执行此操作,它将正常工作.
脚本:
//use .ready() or pageLoad() and pass params etc if you need to $.ajax({ type: 'POST',url: 'Default.aspx/GetControlViaAjax',data: "{}",contentType: "application/json; charset=utf-8",dataType: "json",success: function (data) { $('#yourdiv').html(data.d); } });
的WebMethod:
[WebMethod] public static string GetControlViaAjax() { //example public properties,send null if you don't have any Dictionary<string,object> d = new Dictionary<string,object>(); d.Add("CssClass","YourCSSClass"); d.Add("Title","Your title"); return RenderUserControl("/yourcontrol.ascx",true,d,null,null); //use this one if your controls are compiled into a .dll //return RenderUserControl(null,"Com.YourNameSpace.UI","AwesomeControl"); }
渲染方法:
private static string RenderUserControl(string path,bool useFormLess,Dictionary<string,object> controlParams,string assemblyName,string controlName ) { Page pageHolder = null; if (useFormLess) { pageHolder = new FormlessPage() { AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath }; //needed to resolve "~/" } else { pageHolder = new Page() { AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath }; } UserControl viewControl = null; //use path by default if(String.IsNullOrEmpty(path)) { //load assembly and usercontrol when .ascx is compiled into a .dll string controlAssemblyName = string.Format("{0}.{1},{0}",assemblyName,controlName ); Type type = Type.GetType(controlAssemblyName); viewControl = (UserControl)pageHolder.LoadControl(type,null); } else { viewControl = (UserControl)pageHolder.LoadControl(path); } viewControl.EnableViewState = false; if (controlParams != null && controlParams.Count > 0) { foreach (var pair in controlParams) { Type viewControlType = viewControl.GetType(); PropertyInfo property = viewControlType.GetProperty(pair.Key); if (property != null) { property.SetValue(viewControl,pair.Value,null); } else { throw new Exception(string.Format( "UserControl: {0} does not have a public {1} property.",path,pair.Key)); } } } if (useFormLess) { pageHolder.Controls.Add(viewControl); } else { HtmlForm form = new HtmlForm(); form.Controls.Add(viewControl); pageHolder.Controls.Add(form); } StringWriter output = new StringWriter(); HttpContext.Current.Server.Execute(pageHolder,output,false); return output.ToString(); }
FormlessPage类:
public class FormlessPage : Page { public override void VerifyRenderingInServerForm(Control control) { } }