.net ViewState in page lifecycle

后端 未结 4 784
遇见更好的自我
遇见更好的自我 2020-12-21 02:30

I have a page containing a control called PhoneInfo.ascx. PhoneInfo is dynamically created using LoadControl() and then the initControl() function is called passing in an i

4条回答
  •  粉色の甜心
    2020-12-21 03:08

    I thought, like the answerers, that this problem existed because I was setting the ViewState variable too late to be saved during SaveViewState. However, I added an override for the SaveViewState event, and sure enough I was setting my ViewState variable long before the ViewState was saved. Too long before, it turns out.

    Apparently after initialization, .net runs TrackViewState() which actually starts listening for any viewState variables you add. Since I had set this viewState value BEFORE TrackViewState() had run, everything appeared fine but the values were not actually being added during SaveViewState. I explicitly called TrackViewState() right before setting the variable and everything worked as expected.

    My final solution was to assign a private property to hold the ID value through initialization and then to set the viewState variable during SaveViewState from the property value. This way I can ensure that TrackViewState has been run by .net without having to explicitly call it and mess up the flow of things. I reload the viewState value on page_load and use it to set the value of the property which I can then use in my GetPhone function.

    This article talks about enableViewState.

    private int _id = -1;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (ViewState["PhoneId"] != null)
        _id = SafeConvert.ToInt(ViewState["PhoneId"]);
    }
    
    protected override object SaveViewState()
    {
        ViewState["PhoneId"] = _id;
        return base.SaveViewState();
    }
    
    public Phone GetPhone()
    {
        Phone phone = new Phone();
        phone.Id = _id;
        phone.AreaCode = SafeConvert.ToInt(txt_areaCode.Text);
        phone.Number = SafeConvert.ToInt(txt_number.Text);
        return phone;
    }
    

提交回复
热议问题