What does EnableViewState on a HyperLink do or mean?
What does EnableViewState on a HyperLink do or mean?
<asp:HyperLink ID="开发者_高级运维RegisterHyperLink" runat="server" EnableViewState="false">Register</asp:HyperLink>
What does it mean? and what will it do if I set it to true. Thanks! I looked it up, but the definition was not in simple terms.
ViewState is used to persist the state of control properties across postbacks. Disabling it means that any properties you set programmatically (in code-behind) won't be persisted across page postbacks. However, if you declare all the values declaratively (in your .aspx page) then disabling it won't make any difference.
A quick example:
Say you have this aspx mark-up with ViewState enabled:
<form id="form1" runat="server">
<div>
<asp:HyperLink ID="RegisterHyperLink" runat="server" EnableViewState="true">Register</asp:HyperLink>
<br /><br />
<asp:Button ID="ButtonPostBack" runat="server" Text="Post Back" />
</div>
</form>
And you do this in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RegisterHyperLink.ForeColor = System.Drawing.Color.Red;
}
}
Even though you only set the ForeColor of the HyperLink to the colour red on the first load the HyperLink will still remain red after clicking the Button that performs the postback. That is because ViewState stores the value of the HyperLinks properties and re-creates them after postback.
If you try the exact same thing but with ViewState disabled on the HyperLink, when you click the submit button the HyperLink will revert back to its original colour. That is because viewstate isn't "storing" the fact that you set it to be red.
In practical terms you can normally disable ViewState if:
A) Your page doesn't perform any postbacks B) You set all the properties declaratively
If you really want to understand ViewState I'd recommend reading TRULY Understanding ViewState.
This means that you can set the NavigateUrl
property during a Page request (i.e. in code behind, and not as an attribute on the control's template declaration), that property will persist across following postbacks. If you disable the EnableViewState
property, assign a NavigateUrl
, then on the following postback request, the NavigateUrl
property will be nothing.
I believe this also applies to the control's other properties, like Text
, Target
, and ImageUrl
.
The default value is true
. The Page's EnableViewState
property takes precedent and will override the property on any child controls.
精彩评论