TextBox Custom Attribute is Empty

2019-08-29 09:17发布

问题:

I am setting a custom attribute in the markup like this..

<asp:TextBox runat="server" guid="" ID="txtlocation1" type="text" class="autocomplete short-field require" name="location1" autocomplete="off" datasource="locations" />

Javascript sets the value of it and I am trying to read the value on button click like this...

var val = txtlocation1.Attributes["guid"];

I always get an empty string.. any ideas? PS: I am not setting the attribute in code though.

回答1:

custom attributes will not be sent back to server...you may use a HiddenFeild control instead to hold your data and change it with javascript and on server you will read the updated value



回答2:

The Textbox will push any attributes it doesn't recognize directly to the client; this is a feature of the IAttributeAccessor interface. However, they will not be sent back to the server; a textbox will only post back to the server its value property. Use a <asp:HiddenField /> control or <input type="hidden" /> to post them back to the server. Then you can read the changed value from the hidden field.



回答3:

The attributes are preserved in ViewState, so an empty string is added to the ViewState in your case. Setting the attribute on the client will not have any affect because only the Text (or value) property is posted back to the server. The control will be recreated server-side and the ViewState will be reapplied making your GUID attribute an empty string again.

I suppose you could just set a hidden form field to your GUID. When the button is clicked, it should be available server-side with the correct value.