Difference between ID and control.ClientID OR why use control.ClientID if I can access the control via ID

This is the code from the .aspx file

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login Again</title>

    <script type="text/javascript">
        function Validate() {
            if (document.getElementById("txtLogin").value == "") {
                alert("Enter login name.");
            }

            if (document.getElementById("<%=txtLogin.ClientID%>").value == "") {
                alert("Enter login name.");
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="txtLogin" runat="server"></asp:TextBox>
    <asp:Button ID="btnSubmit" runat="server" Text="Login" OnClientClick="Validate()" />
    </form>
</body>
</html>
  • In the Validate () function, I can access a text field using a control identifier i.e.; getElementById("txtLogin")so should one use a second approach that accesses control through control.ClientIDand why?

  • My first understanding was that server access control I should use this syntax <%= %>, but now I come to know from this example that I can access the server on the server side simply through getElementById("ID-of-control").

+3
source share
3 answers

, HTML, , , aspx. , , . ClientId ID, HTML, javascript.

+3

...

...

ASP.NET ID, , . , HTML id ; id script HTML. , , ASP.NET HTML, ID id HTML. ID ....

- ClientID, , .

+1

ASP.NET ? .NET 4 .

I think this is a coincidence in this case, because you are not using any custom controls or other containers. Once you do this, you can no longer guarantee that the identifier of the controls will remain the same, and therefore you should use the second approach as best practice, because if your page is changed in the form in which I stated that your javascript will no longer work and it may be difficult to understand why at a later date.

+1
source

Source: https://habr.com/ru/post/1765445/


All Articles