开发者

ViewState not persisting custom additions over postback

开发者 https://www.devze.com 2023-04-10 17:48 出处:网络
I have a question, and it may be because I\'m not understanding the way viewstate works.I have some code that sets a viewstate variable in the setter for a property in a custom control I have made.

I have a question, and it may be because I'm not understanding the way viewstate works. I have some code that sets a viewstate variable in the setter for a property in a custom control I have made.

 public bool EditMode
    {
        get { return (bool)(ViewState["editMode" + this.ID] ?? false); }
        set {ViewState["editMode" + this.ID] = value;} 
    }

The editmode is being set during a button click event.

 public void shippingButton_Click(object sender, EventArgs e) 
    {
        if (((Button)sender).CommandName== "Edit")
        {
            ctrlShippingAddress.EditMode = true;
        }
        else
        {
            Page.Validate();
            if (Page.IsValid)
            {
                ctrlShippingAddress.SaveAddr开发者_如何学Pythoness();
                ctrlShippingAddress.EditMode = false;
            }
        }
    }

I've tried manually setting it on page load in case I wasn't adding this to the viewstate at the correct point in the page cycle, but as I understand it events occur before render. I have also tried adding ViewStateMode="Enabled" to the control, then to the page using it, then to the master page with no luck.

If I debug at the point of the get/set I see that viewstate is an empty collection (which doesn't make sense because it's also saving form data that is persisting as it should).

I appreciate any help.


You don't need to append the control ID to the ViewState key. I assume you're doing that for uniqueness, but it's not necessary.

The above may fix your problem, but if not try something like this instead:

public bool EditMode 
{ 
    get 
    { 
        bool editMode = false;
        if (ViewState["editMode"] != null)
            editMode = (bool)ViewState["editMode"];
        return editMode;
    } 
    set 
    {
        ViewState["editMode"] = value;
    }  
} 


After reviewing with a co-worker I discovered that the issue was in the pages node of the web.config

<pages enableViewState="false"> 

needed to be set to true

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号