Is it possible to prevent a Javascript function from executing in C# if record exista in DB?

Donald Symmons 2,856 Reputation points
2024-02-27T05:26:56.4+00:00

Hello community, please I will like to ask if it possible that a Javascript function is prevented from executing from code behind (C#), if a record exists in a database? The reason why I haven't posted any code is that I want to first find out if it is possible, then I can post my code that prevents an event from happening or hides elements if record exists in database, to see if I can get help. Thank you

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,391 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,265 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,271 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,636 Reputation points Microsoft Vendor
    2024-02-28T07:35:32.5833333+00:00

    Hi @Donald Symmons,

    I modified your code and the code below will work fine for your reference.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
        <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
        <script>
            function Func() {
                var positions = JSON.parse(localStorage.positions || "{}");
                $(function () {
                    var d = $("[id*=draggable]").attr("id", function (i) {
                        return "draggable_" + i
                    })
                    $.each(positions, function (id, pos) {
                        $("#" + id).css(pos)
                    })
                    d.draggable({
                        containment: "#containment-wrapper",
                        scroll: false,
                        stop: function (event, ui) {
                            positions[this.id] = ui.position
                            localStorage.positions = JSON.stringify(positions)
                        }
                    });
                    $("#clear").click(function () {
                        window.localStorage.clear();
                        window.location.reload();
                    });
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div class="customer" style="width: 100%; line-height: 1.3; margin-bottom: 3%;">
                <div id="draggable1" class="ui-widget-content" style="float: left; text-align: start; margin-bottom: 5%; font-size: 1.6rem;">
                    <label style="font-size: 10pt; color: #000000; font-weight: 400;">Bill To:</label>
                    <div style="font-weight: 600;">
                        <asp:Label ID="nameLbl" runat="server" Font-Size="11pt" Text="Customer Name"></asp:Label>
                    </div>
                    <div>
                        <asp:Label ID="addressLbl" runat="server" Font-Size="10pt" Text="Customer address"></asp:Label>
                    </div>
                    <div>
                        <asp:Label ID="phoneLbl" runat="server" Text="Phone number" Font-Size="10pt"></asp:Label>
                    </div>
                    <div>
                        <asp:Label ID="mailLbl" runat="server" Font-Size="10pt" Text="email address"></asp:Label>
                    </div>
                </div>
                <div id="draggable2" class="ui-widget-content" style="float: right; text-align: right; margin-bottom: 5%;">
                    <asp:Label ID="Label3" runat="server" Font-Size="11pt" Text="#"></asp:Label><asp:Label ID="lblprefix" runat="server" Font-Size="11pt" Text=""></asp:Label>
                    <div>
                        <asp:Label ID="issuelbl" runat="server" Font-Size="10pt" Text="Issued date"></asp:Label>
                    </div>
                    <div>
                        <asp:Label ID="datLbl" runat="server" Font-Size="10pt" Text=""></asp:Label>
                    </div>
                    <div>
                        <asp:Label ID="Label15" runat="server" Font-Size="10pt" Text="Due date"></asp:Label>
                    </div>
                    <div>
                        <asp:Label ID="dateLbl" runat="server" Font-Size="10pt" type="date" Text=""></asp:Label>
                    </div>
                </div>
            </div>
        </form>
    </body>
    </html>
    
    protected void Page_Load(object sender, EventArgs e)
    {
        //Session["user"] = 6; Test Data      
        MyDesignFunction();
    }
    private void MyDesignFunction( )
    {
        try
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM SavedDesign WHERE Id = @Id", con))
                {
                    cmd.Parameters.AddWithValue("@Id",Convert.ToInt32(Session["user"]));
                    con.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                       
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Func()",true);
                    }
                    con.Close();
                }
            }
        }
        catch (SqlException ex)
        {
            string msg = "Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
    }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Albert Kallal 4,651 Reputation points
    2024-02-27T16:48:02.88+00:00

    You can always add a "server side" expression to the client side JavaScript code. So, say for JavaScript, I want to check/display/test/enjoy the fact of the database having more then 10 reocrds. So, I can have this server side code:

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsPostBack Then
                LoadData
            End If
        End Sub
    
        Sub LoadData()
            Dim strSQL As String =
                "SELECT * FROM tblHotelsA ORDER BY HotelName"
            Dim rstData As DataTable
            rstData = MyRst(strSQL)
            If rstData.Rows.Count > 10 Then
                ViewState("Has10") = True
            Else
                ViewState("Has10") = False
            End If
        End Sub
    
        Public Function HasRecords() As Boolean
            Return ViewState("Has10")
        End Function
    
    

    It not really all that important what the above does, but NOTE CLOSE the public function HasRecords. So, now in client side, I can have this code:

            <script>
                var Has10 = '<%=Me.HasRecords() %>'
                if (Has10 = 'True') {
                    alert("The database has 10 or more records")
                }
                else {
                    alert("The database has less then 10 records")
                   
                }
            </script>
    
    

    So, note how the JavaScript can now check/test/enjoy/use the result of the server side public function called HasRecords. So the suggestion here is to place/use/have some client side varible that is set from a public server side function. That way, your code can with ease check/test/enjoy this information in the client side JavaScript. You can thus in your client side JavaScript add a simple "if" statement based on this value.

      if (SomeValue = 'True') {
            your javaScript code here that you now want to run.
    
    0 comments No comments

  2. AgaveJoe 26,136 Reputation points
    2024-02-27T14:34:30.7833333+00:00

    I do not understand your explanation. Perhaps if you give it with sample code to demonstrate your explanation it would be nice

    It seems your draggable design is based on a div's Id attribute to contain "draggable" ($("[id*=draggable]")). It is a reasonable to assumption that if the Id did not contain "draggable" then the div is no longer draggable. Then the question is how to dynamically update the DOM using the standard tooling within ASP.NET Web Forms.

    The two <div> elements are basic HTML so they are not available in the code behind. But, the code that fetches records is in the code behind. We need a way to update the HTML depending on what records we find in the code behind. A simple variable is the answer.

    In the Code behind, I defined two properties Div1 and Div2 that return a string. If the variable behind Div1 (_div1) or Div2 (_div2) is empty then return draggable1 or draggable2. If Div1 or Div2 is set then return whatever string the dependent variables are set to.

    using System;
    namespace WebFormsDemo.RenderHtml
    {
        public partial class Default : System.Web.UI.Page
        {
            private string _div1 = string.Empty;
            private string _div2 = string.Empty;
            public string Div1
            {
                get 
                {
                    return _div1 == string.Empty ? "draggable1" : _div1;
                } 
                set
                {
                    _div1 = value;
                }
            }
            public string Div2
            {
                get
                {
                    return _div2 == string.Empty ? "draggable2" : _div2;
                }
                set
                {
                    _div2 = value;
                }
            }
            protected void Page_Load(object sender, EventArgs e)
            {
               
            }
            protected void Button1_Click(object sender, EventArgs e)
            {
                Div1 = "static1";
            }
        }
    }
    

    All that's left is to expose the variable to the markup using a code block (<% %>).

    <div id="<%=Div1 %>" class="ui-widget-content">
        <%=Div1 %>
    </div>
    <div id="<%=Div2 %>" class="ui-widget-content">
        <%=Div2 %>
    </div>
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    

    There are many ways to solve this basic HTML rendering problem. The key is taking the time to understand the tools you decided to use for your project. For example, you could replace the div with a Panel Server control which renders as a <div>. This gives you access to the Panel in the code behind where you get to update the elements attributes anyway you like. However, if you did go the Panel route then I would use class attributes and selectors rather than the ID.

    One last thing yo note, your HTML markup is invalid. IDs should be unique. You have two "draggable1" IDs.

    0 comments No comments