后物业空回发 - 动态加载控制 [英] Property null after postback - Dynamically loaded control

查看:137
本文介绍了后物业空回发 - 动态加载控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被问了很多次之前,但我怀疑我有一个独特的场景。

我加载一个子控件(ASCX)和控制设置属性。这工作完全正常,直到回传,其中属性为null。

随函附上头等舱它加载ChildControl:

 保护覆盖无效的CreateChildControls()
{
    控制的MyUserControl =(的MyUserControl)Page.LoadControl(_ascxPath);
    control.MyProperty = base.MyProperty
    Controls.Add被(对照组);
}

然后,在我的孩子控制我有以下code:

 公共部分类的MyUserControl:用户控件
{
    公共MyType的myProperty的{搞定;组; }
    保护无效的Page_Load(对象发件人,EventArgs的发送)
    {
        //对下一行异常,因为属性为null(仅在回发)
        VAR someValue中= MyProperty.SubProperty;


解决方案

确定。让我试着解释一下。

1.当页面被创建,您得到充分的网页。生命周期

2.点击一些控件来创建用户控制,你会得到它

3.现在你正在进入价值相关的控制,并获得回传

4.在服务器端回发的处理,但你可以看到ViewState的行为只要加载页面时出现。

 一个视图状态的主要用途是处理控制的事件,看他们是否被更改,或者保存其状态或别的东西。

5.如果在那一刻,当ViewState是加载,可以控制仍然没有建成,那么所有它的活动和值将被忽略。

解决方案要么使静态控制,只是将其隐藏,要么创建视图状态的行动开始前。

I'm aware this question has been asked many times before but I suspect I have a unique scenario.

I'm loading a Child Control (ASCX) and setting a Property on that Control. This works perfectly fine until postback where the property is null.

Herewith the First Class which loads the ChildControl :

protected override void CreateChildControls()
{
    MyUserControl control = (MyUserControl)Page.LoadControl(_ascxPath);
    control.MyProperty = base.MyProperty
    Controls.Add(control);
}

Then, on my Child Control I've got the following code:

public partial class MyUserControl : UserControl
{
    public MyType MyProperty { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Exception on next line because Property is null (only on postback)
        var somevalue = MyProperty.SubProperty;

解决方案

Ok. Let me try to explain it.
1. Once page is created, you get full page lifecycle
2. You click on some control to create user control, and you get it
3. Now you are entering value to this control, and getting postback
4. On server side postback is handled, but as you can see viewstate actions appear as soon as page is loaded.
One of main purposes of viewstate is handling control events, to see if they are changed, or save their states or something else.
5. If on the moment, when viewstate is loaded you control is still not constructed, then all it's events and values would be ignored.

Solution either make it static control and just hide it, either create it before viewstate actions started.

这篇关于后物业空回发 - 动态加载控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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