/// <summary> /// 根据用户控件的虚拟路径获取用户控件的Html内容 /// </summary> /// <param name="userControlVirtualPath">用户控件的虚拟路径</param> /// <returns>用户控件的Html内容</returns> public string GetUserControlContents(string userControlVirtualPath) { var ownerPage = new Page(); var userControl = (UserControl)ownerPage.LoadControl(userControlVirtualPath); userControl.EnableViewState = false; var form = new HtmlForm(); form.Controls.Add(userControl); ownerPage.Controls.Add(form); var writer = new StringWriter(); System.Web.HttpContext.Current.Server.Execute(ownerPage, writer, false); return FilterHtml(writer.ToString()); }
/// <summary> /// 过滤Html /// </summary> /// <param name="html">用户控件Html内容</param> /// <returns>过滤后的Html内容</returns> private string FilterHtml(string html) { if (string.IsNullOrEmpty(html)) { return string.Empty; } var doc = new XmlDocument(); doc.LoadXml(html); var form = doc.SelectSingleNode("/form"); var nodes = doc.SelectNodes("/form/div[@class='aspNetHidden']"); if (nodes != null && form != null) { foreach (XmlNode oldChild in nodes) { form.RemoveChild(oldChild); } } html = doc.InnerXml; html = Regex.Replace(html, @"<[/]?(form)[^>]*?>", "", RegexOptions.IgnoreCase); return html; }