传递数据从子页的母版页用户控制 [英] Pass Data into User Control on Master Page from Sub Page

查看:148
本文介绍了传递数据从子页的母版页用户控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有母版页上的用户控制和我想在一个值从子页面的用户控件通过,我将如何能够传递的价值观?

I have a user control on the master page and I would like to pass in a value into that user control from the subpage, how would I be able to pass the values?

这是控制在母版页

<%@ Register TagPrefix="test" TagName="Data" Src="controls/TEST.ascx" %>

这code变量是用户控制的范围内。

This code variable is within the user control

public partial class Controls_TEST : System.Web.UI.UserControl
{
    private string _Title;
    public string Title
    {
        get { return _Title; }
        set { _Title = value; }
    }
}

子页面内code

Code within the subpage

public partial class sub_page : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
         Controls_Test m = LoadControl("~/Controls/TEST.ascx");
         m.Title = "TEST";
    }
}

请注意子页面内的样品code不起作用,因为它无法找到的子页面内的用户控件。

Note the sample code within subpage does not work because it cannot find that user control within the subpage.

我试过Page.Master.FindControl,它也没有为我工作。请帮助。

I've tried Page.Master.FindControl and it also does not work for me. PLease help.

推荐答案

使用性能从网​​页通信你的母版和使用性能从你的母版传达给用户控件

Use properties to communicate from your Page to your MasterPage and use properties to communicate from your MasterPage to the UserControl.

要得到返回它在你的母版你应该提供的公共属性的控件的引用:

To get a reference to the control in your MasterPage you should provide a public property that returns it:

例如(在母版):

public Controls_Test MyControl
{
     get
     {
         return Controls_TEST1;
     }
}

你可以这样调用从内容网页之一这个属性(f.e如果你的主人型被命名为 SITEMASTER 的。):

protected void Page_Load(object sender, EventArgs e)
{
    ((SiteMaster)Page.Master).MyControl.Title = "TEST";
}

根据经验的规则:你越封装你的控制,更强大,故障安全,maintanable和可扩展您的code将

As a rule of thumb: the more you encapsulate your controls, the more robust ,failsafe, maintanable and extendable your code will be.

因此​​,它会更好只提供给标题访问,而不是整个用户控件。

Hence it would be better to provide only access to the Title rather than to the whole UserControl.

母版

public String Title
{
     get
     {
         return Controls_TEST1.Title;
     }
    set
    {
        Controls_TEST1.Title = value;
    }
}

ContentPage

((SiteMaster)Page.Master).Title = "TEST";

在这种方式,你可以改变的逻辑和控制你的用户控件母版,而不必在你的网页的问题已经访问过的用户控件直接

On this way you could change the logic and controls in your UserControl and MasterPage without having problems in your pages that already have accessed the UserControl directly.

这篇关于传递数据从子页的母版页用户控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆