Monday, November 25, 2013

Dynamic jQuery calls from code behind VB.NET


Simple Function call: You can call the jQuery from code behind with the help of ClientScript.RegisterStartupScript():
  
ClientScript.RegisterStartupScript(this.GetType(), 
           "blah", "YourJsFunction();", true);
Assign via the control: If you have multiple controls on a page and need to make an individual jQuery call based on condition (not for every time; let say after the button click)
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" 
                                        runat="Server">
       
    <asp:Literal runat="server" ID="ltlJsFadeCode"></asp:Literal>
     
    Result: 
     <asp:Label runat="server" ID="lblResult"></asp:Label>
     
    Id:     
     <asp:TextBox runat="server" ID="tbId"></asp:TextBox>
     
    Save Button: 
     <asp:Button runat="server" ID="btnSave" Text="Save" />
</asp:Content>

Code behind:
       
        Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As 
                               System.EventArgs) Handles btnSave.Click
          ltlJsFadeCode.Text = JsFadeCode(lblResult.ClientID)
          lblResult.Text = "<span style=""font-weight:bold;color: #0C0;"">
                                          Saved</span>"
        End Sub 

        Protected Function JsFadeCode(ByVal clientId As String) As String
        Dim sb As New StringBuilder
        sb.Append(vbNewLine)
        sb.Append("<scr")
        sb.Append(vbNewLine)
        sb.Append("$(document).ready(function() {")
        sb.Append(vbNewLine)
        sb.Append("$('#")
        sb.Append(clientId)
        sb.Append("').animate({ opacity: 1.0 }, 3000).fadeOut('slow');")
        sb.Append(vbNewLine)
        sb.Append("});")
        sb.Append(vbNewLine)
        sb.Append("</scr"
        sb.Append("ipt>")
        sb.Append(vbNewLine)
        sb.Append(vbNewLine)
        Return sb.ToString
    End Function
Hence, the literal control ltlJsFadeCode behaves like jQuery ready function:
<script type=""text/javascript">
   $(document).ready(function(){
     $('#lblResult').animate({ opacity: 1.0 }, 3000).
                                fadeOut('slow');
       };
<script>
Happy Coding!!