虽然我们在Substitution控件中使用的方法应该返回字符串,那么如何在服务器控件上的Web表单中使用donut caching,这应该是服务器端? 例如Loginview控件?
答案 0 :(得分:6)
答案 1 :(得分:0)
遗漏了Micah的一个问题是,替换函数必须为static
,接受HttpContext
参数,然后返回string
。有关详细信息,请参阅this msdn page。
我还将Micah的助手类扩展得更灵活一些。
<强>标记强>
<asp:Substitution ID="Substitution1" MethodName="myFunction" runat="server" />
<强>实行强>
public static string myFunction(HttpContext httpContext){
ViewManager vm = new ViewManager();
//example using a Button control
Button b = new Button();
b.Text = "click me"; //we can set properties like this
//we can also set properties with a Dictionary Collection
Dictionary<string,object> data = new Dictionary<string,object>();
data.add("Visible",true);
String s = vm.RenderView(b,data); //don't do anything (just for example)
//we can also use this class for UserControls
UserControl myControl = vm.GetUserControl("~mypath");
data.clear();
data.add("myProp","some value");
return vm.RenderView(myControl,data); //return for Substitution control
}
<强>类强>
using System.IO;
using System.ComponentModel;
public class ViewManager
{
private PageForRenderingUserControl pageHolder;
public ViewManager()
{
pageHolder = new PageForRenderingUserControl();
}
public UserControl GetUserControl(string path)
{
return (UserControl)pageHolder.LoadControl(path);
}
public string RenderView(Control viewControl, Dictionary<string, object> data)
{
pageHolder.Controls.Clear();
//Dim viewControl As UserControl = DirectCast(pageHolder.LoadControl(Path), UserControl)
if (data != null) {
Type viewControlType = viewControl.GetType();
dynamic properties = TypeDescriptor.GetProperties(viewControl);
foreach (string x in data.Keys) {
if ((properties.Item(x) != null)) {
properties.Item(x).SetValue(viewControl, data[x]);
}
}
}
pageHolder.Controls.Add(viewControl);
StringWriter result = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, result, false);
return result.ToString();
}
private class PageForRenderingUserControl : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
// Do nothing
}
public override bool EnableEventValidation {
get { return false; }
// Do nothing
set { }
}
}
}
再次感谢Micah代码
答案 2 :(得分:-1)
我相当确定你不能这样做 - Substitution控件只能 允许你将一个字符串插入一个outputcached页面。
如果你考虑一下服务器控件的整个输出,这是有道理的,这可能是<table>
,它会破坏你所有精心设计的标记和/或需要加载<script>
加载到{页面 - 而注入单个字符串是相对简单的。