Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net - Access an asp:hiddenfield control in JavaScript

What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback.

Here is my current source code:

<script language="javascript" type="text/javascript">
    function AccessMyHiddenField()
    {
        var HiddenValue = document.getElementById("<%= MyHiddenField.ClientID %>").value;

        //do my thing thing.....
    }
</script>
<asp:PlaceHolder ID="MyPlaceHolder" runat="server" Visible="false">
    <asp:HiddenField ID="MyHiddenField" runat="server" />
</asp:PlaceHolder>

EDIT: How do I set the style for a div tag in the ascx code behind in C#? This is the description from the code behind: CssStyleCollection HtmlControl.Style

UPDATE: I replaced the asp:hiddenfield with an asp:label and I am getting an "undefined" when I display the HiddenValue variable in a alert box. How would I resolve this.

UPDATE 2: I went ahead and refactored the code, I replaced the hidden field control with a text box control and set the style to "display: none;". I also removed the JavaScript function (it was used by a CustomValidator control) and replaced it with a RequiredFieldValidator control.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is

  1. Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css.
  2. If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :

    placeholderId.Attributes["style"] = "display:none";

Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...