简体   繁体   中英

Where is the public properties of a asp.net web control saved?

I have a web control that derives from another web control (in this case GridView). When I add new properties to that web control, such as

public string name {get;set;} 

Is that property being saved somewhere? If so, is it stored in Control State automatically or do I need to override the SaveControlState function ...

I was able to determine the behavior of the application, but would like to know the correct implementation.

There are some other ways, but out of scope for this question, see below:

//stores it in memory
public string name {get;set;} 

//viewstate backed property, preserved on postback when viewstate is enabled
public string name {
    get
    {
        return (string)ViewState["name "] ?? String.Empty; //default value
    }
    set
    {
        ViewState["name "] = value;
    }
}

Properties declared in that way are backed by a private field that's created by the compiler. They only persist for the life of the class.

If you want to persist between postbacks, use ViewState as a backing store. You could also, as you suggest, override the control state methods, but ViewState is probably simpler.

ETA: Mr. Schott in his reply has a good example of using ViewState.

What do you mean by "Is that property being saved somewhere?" If you add the property to your class, then it's a member of your class and is included on the heap in the scope of an instance of that class.

Are you just asking about the syntax of Auto-Implemented Properties ? When you write this:

public string name {get;set;}

It's really just syntactic sugar. By the time the code is being executed, the compiler has turned it into something more like this:

private string _name;
public string name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}

Auto-Implemented Properties are just a way to reduce the amount of code you need to type, allowing you to focus on what you're trying to express without having to wrap it in so much language overhead that doesn't really contribute to the expressiveness of the code. The end result is exactly the same as implementing the entire property manually, it's just a shortcut if you don't need to add any custom logic to the property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM