Search code examples
jquery.nettablednd

ASP.NET - show / hide jquery .ready code programmatically


I have aspnet form, were jquery function is load:

<script type="text/javascript">
    $(document).ready(function () {
        var table = document.getElementById('<%=grdNews.ClientID%>');
        var tableDnD = new TableDnD();
        tableDnD.init(table);
    })
</script>

FYI: this is not my code and I haven't developed TableDnD class. This clss attaches drag & drop functionality for one table in aspnet form.

Everything works fine here.

However, now I have a new requirement: for some users I do not need to do this jquery, for some - this jquery is still necessary. How can I achieve this programmatically? This would be something like:

ON PAGE LOAD:
if (User == SpecificUser) 
{
     ALLOW_ABOVE_JQUERY (LOAD JQUERY FUNCTION ON LOAD) //?HOW
}
else 
{
     DO_NOT_ALLOW_ABOVE_JQUERY (DISABLE LOADING JQUERY FUNCTION ON LOAD) //?HOW
}

It is something about javascript in code behind, but this is $(document).ready that makes me confused.


Solution

  • You can use server tags in the markup:

    <% if (User == SpecificUser) { %>
    <script type="text/javascript">
      $(document).ready(function () {
        var table = document.getElementById('<%=grdNews.ClientID%>');
        var tableDnD = new TableDnD();
        tableDnD.init(table);
      });
    </script>
    <% } %>
    

    Alternatively you can put it in a place holder:

    <asp:PlaceHolder ID="ScriptContainer" runat="server">
    <script type="text/javascript">
      $(document).ready(function () {
        var table = document.getElementById('<%=grdNews.ClientID%>');
        var tableDnD = new TableDnD();
        tableDnD.init(table);
      });
    </script>
    </asp:PlaceHolder>
    

    Then hide the content from code behind:

    if (User != SpecificUser) {
      ScriptContainer.Visible = false;
    }