加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

如何在Substitution控件中使用ASP.Net服务器控件?

发布时间:2020-12-16 06:57:30 所属栏目:asp.Net 来源:网络整理
导读:虽然我们在Substitution控件中使用的方法应该返回字符串,那么如何在服务器控件上使用Web表单中的 donut caching呢? 例如Loginview控件? 解决方法 UPDATE 现在这是一个完全有效的例子.这里发生了一些事情: 使用替换控件的回调来呈现所需的usercontrol的输
虽然我们在Substitution控件中使用的方法应该返回字符串,那么如何在服务器控件上使用Web表单中的 donut caching呢?
例如Loginview控件?

解决方法

UPDATE
现在这是一个完全有效的例子.这里发生了一些事情:

>使用替换控件的回调来呈现所需的usercontrol的输出.
>使用覆盖VerifyRenderingInServerForm和EnableEventValidation的自定义页面类来加载控件,以防止在usercontrol包含需要表单标记或事件验证的服务器控件时引发错误.

这是标记:

<asp:Substitution runat="server" methodname="GetCustomersByCountry" />

这是回调

public string GetCustomersByCountry(string country)
{
   CustomerCollection customers = DataContext.GetCustomersByCountry(country);

    if (customers.Count > 0)
        //RenderView returns the rendered HTML in the context of the callback
        return ViewManager.RenderView("customers.ascx",customers);
    else
        return ViewManager.RenderView("nocustomersfound.ascx");
}

这是用于呈现用户控件的帮助器类

public class ViewManager
{
    private class PageForRenderingUserControl : Page
    {
        public override void VerifyRenderingInServerForm(Control control)
        { /* Do nothing */ }

        public override bool EnableEventValidation
        {
            get { return false; }
            set { /* Do nothing */}
        }
    }

    public static string RenderView(string path,object data)
    {
        PageForRenderingUserControl pageHolder = new PageForUserControlRendering();
        UserControl viewControl = (UserControl) pageHolder.LoadControl(path);

        if (data != null)
        {
            Type viewControlType = viewControl.GetType();
            FieldInfo field = viewControlType.GetField("Data");
            if (field != null)
            {
                field.SetValue(viewControl,data);
            }
            else
            {
                throw new Exception("ViewFile: " + path + "has no data property");
            }
        }

        pageHolder.Controls.Add(viewControl);
        StringWriter result = new StringWriter();
        HttpContext.Current.Server.Execute(pageHolder,result,false);
        return result.ToString();
    }
}

请参阅以下相关问题:

> Turn off page-level caching in a
user control
> UserControl’s RenderControl is asking for a form tag in (C# .NET)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读