Showing posts with label How to JQuery. Show all posts
Showing posts with label How to JQuery. Show all posts

Thursday, July 31, 2014

How to display data on Asp.net web form without postback? using JSON, JQuery.ajax and WebMethod

To display data on web form without postback, we will use JSON, JQuery $.ajax, WebMethod and JavascriptSerializer. Sometime we need some data to be displayed when user wants it. Without user request, we don't want to show that data on aspx page. In this situation, we should give one button, so whenever user wants it, he will click and get the result.

How do we achieve this? just follows the steps:

Step 1: Create a project with Asp.net empty web application. and add "Default.aspx" page.

Step 2: In Default.aspx page, add following code.
<!DOCTYPE html>

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

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script> 
             function getRandomNumber() {
                 
                $.ajax({

                    url: "Default.aspx/getRandomNumber",
                    data: '',
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (mydata) {

                        var i = JSON.parse(mydata.d);
                        $("#lblRandomNumber").text(i);
                         
                    }
                });
            }  
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnRandomNumber" runat="server" 
                OnClientClick="javascript:getRandomNumber(); return false;"   
                Text="Get Random Number" />
            <asp:Label ID="lblRandomNumber" runat="server" ></asp:Label>
        </div>
    </form>
</body>
</html>


Step 3: Now, In Default.aspx.vb page, add following code.
Imports System.Web.Services
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services

Public Class _Default
    Inherits System.Web.UI.Page
     
    <WebMethod> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Shared Function getRandomNumber() As String

        Dim s As String = New Random().Next(100).ToString()
        Dim ser As New JavaScriptSerializer()
        Dim jsonString = ser.Serialize(s)
        Return jsonString
    End Function
     
End Class


Step 4: Now run it, and click on "get random number" button to get the random number without postback.



Friday, July 18, 2014

Wednesday, July 16, 2014

How can I set the SRC attribute to an IFRAME with JQuery?

You can set the SRC attribute of the iFrame using JQuery like following:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>

     $(document).ready(function(){

          $("#btn").click(function () {
          
             $("#iframe").attr("src", "Home.aspx");
             return false;

          });

      });

</script>



Thursday, June 26, 2014

How to redirect parent window on particular page when we close the modal popup window? using JQuery or Javascript (NOT on reload or post back)

I was looking for JQuery solution which will fire only when I close a modal popup window. I found some JQuery examples but none of them gave me correct JQuery solution. What I was looking is that whenever I close the modal popup Window, it prompts with message before closing and redirect to particular page. So I got the following JQuery solution, But the issue in this solution is that it will fire on both event "close" and "reload or post back". This is wrong. I want a JQuery solution which should work only on closing a modal popup window, not on reload or post back.

     $(window).unload(function() {
           //redirection code here
           alert('your message');   
     });

So after some research, I made it and solved the issue with following. I hope this will help you as well.
     $(window).unload(function(event) {
        if (event.target.readyState=='complete') {

            alert('Closing Window and redirecting...');
            var opener = window.dialogArguments;
            opener.parent.location = '../YourRedirected.aspx?id=<%=Record_ID %>';
            top.window.close();

        }
        else {
            alert('Reloading Window');
        }   
     });

Wednesday, June 18, 2014

How to create simple chat application using SignalR 2.0 in Asp.net?

Today I will show you how to create simple chat application using SignalR. The tutorial demonstrates the following SignalR development tasks:

• Adding the SignalR library to an ASP.NET web application.

• Creating a hub class to push content to clients.

• Creating an OWIN startup class to configure the application.

• Using the SignalR jQuery library in a web page to send messages and display updates from the hub.

The following screen shot shows the chat application running in a browser.



Steps are following:

Step 1: Create a new project in .NET 4.5 “Asp.net Empty Web Application” like following.



Step 2: As I am using Visual Studio 2012, I have to manually run the following command to install “Microsoft.AspNet.SignalR” which will add necessary script files and assembly references to support SignalR.

install-package Microsoft.AspNet.SignalR


Go to “Tools” -> Library Package Manager -> Click on Package Manager Console

Choose default project to Your SimpleChat project and write “install-package Microsoft.AspNet.SignalR” in the console and press “Enter” to install. Console looks like following.



Now we need "json2.js". To install this file in our project follow THIS ARTICLE. This is necessary to work smoothly with SignalR application.

Step 3: Create “Users” folder in your project and Create User.cs file in it like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SimpleChat.Users
{
    public class User
    {
        public string Name { get; set; }
        public string Id { get; set; }
    }
}

Step 4. Create “UserRepository.cs” file in “Users” foler like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SimpleChat.Users
{
    public static class UserRepository
    {
        static List<User> lstUser = new List<User>();

        public static void add(User u)
        {
            lstUser.Add(u);
        }

        public static User getById(string id)
        {
            return lstUser.Where(usr => usr.Id == id).FirstOrDefault();

        }
        public static User getByName(string name)
        {
            return lstUser.Where(usr => usr.Name == name).FirstOrDefault();

        }
        public static List<User> getAll()
        {
            return lstUser;
        }
        public static void remove(User u)
        {
            lstUser.Remove(u);
        }
    }
}

Step 5. Create “ChatHub.cs” file in your project like this.
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SimpleChat
{
    public class ChatHub : Hub
    {
        public void Send(string ToName, string message, string FromName)
        {
            //Check ToName, If ToName is specified, send message to that specified Name
            //If ToName is not specified, Send to All Users
            if (ToName != null)
            {
                //Get the ConnectionId of ToName
                string id = Users.UserRepository.getByName(ToName).Id;
                
                //Send message to specified User
                Clients.Client(id).broadcastMessage(FromName, message);

                //Check, if it is not self
                if (id != Context.ConnectionId.ToString())
                {
                    Clients.Client(Context.ConnectionId.ToString()).broadcastMessage("Me", message);
                }
            }
            else
            {
                //Send to all because no user selected.
                Clients.All.broadcastMessage(FromName, message);
            } 
        }

        //Add User in listview
        public void AddUser(string userName)
        {
            Users.User u = new Users.User();
            u.Id = Context.ConnectionId.ToString();
            u.Name = userName;
            Users.UserRepository.add(u);

            Clients.All.updateuserslist(userName);
        }

        //If user leaves the browser, remove from listview or from online users list.
        public override System.Threading.Tasks.Task OnDisconnected()
        {
            Users.User u = Users.UserRepository.getById(Context.ConnectionId.ToString());
            if (u != null)
            {
                RemoveUser(u.Name);
                Users.UserRepository.remove(u);

            }

            return base.OnDisconnected();
        }
        public void RemoveUser(string name)
        {
            Clients.All.updateuserslist_remove(name);
        }

    }
}
Step 6. Create “Startup.cs” file in your project like this.
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SimpleChat.Startup))]
namespace SimpleChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

Step 7. Create “index.aspx” file in your project like this.
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            border: 0px solid #808080;
        }
    </style>

</head>
<body>

    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/json2.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.0.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub. 
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message. 
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:  ' + encodedMsg + '</li>');
            };

            //Update listview to add user
            chat.client.updateuserslist = function (name) {
                $('#ddlUsers').append(
                    $('<option></option>').val(name).html(name)
                );

            };

            //Update listview to remove user
            chat.client.updateuserslist_remove = function (name) {
                $('#ddlUsers option[value=' + name + ']').remove();

            };
             
            // Set initial focus to message input box.  
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#ddlUsers').val(), $('#message').val(), $('#displayname').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
                $('#btnEnter').click(function () {
                    // Call the AddUser method on the hub. 
                    chat.server.addUser($('#displayname').val());
                    $('#btnEnter').hide();
                    $('#displayname').hide();
                    $('#FromName').text($('#displayname').val());
                });
            });
        });
    </script>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="displayname" runat="server"></asp:TextBox>

            <input type="button" id="btnEnter" value="Enter Your Name" />
            <br />
            <br />
             
            <table>
                <tr>
                    <td style="vertical-align: top;">Online Users:<br />
                        <asp:ListBox ID="ddlUsers" runat="server"></asp:ListBox>
                    </td>
                    <td style="border:solid 1px black;">
                        <div class="container" style="height: 330px; width: 300px;">
                            <ul id="discussion" style="overflow: auto; height: 280px; width: 250px;">
                            </ul>
                            <span id="FromName"></span>
                            <input type="text" id="message" />
                            <input type="button" id="sendmessage" value="Send" />

                        </div>
                    </td>
                </tr>
            </table>




        </div>
    </form>
</body>
</html>

Step 8. In code behind of “index.aspx” file, which is “index.aspx.cs” file like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SimpleChat
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                ddlUsers.DataSource = Users.UserRepository.getAll();
                ddlUsers.DataTextField = "Name";
                ddlUsers.DataValueField = "Name";
                ddlUsers.DataBind();


            }



        }


    }
}


That's it! you are ready to run it, BUT before you run your application, make sure that your referencing script files in index.aspx are matching with the project script files. sometimes .js files are updating their version frequently.

In our case, we are referencing following script files:
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/json2.js"></script>
    
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.0.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>

And we have following script files in our project structure.


How it works:


1. Run the application.

2. It will ask you for your "Name".

3. Open another browser and paste the same URL. and again give some name.

4. You can see that all the names will be added in "Online Users" list.

5. Once some user will close the browser, User will be removed from the list automatically.

6. Now you can send message to anybody or to all.

7. To send message to all, don't select any user. and To send messsage to particular User, select it from Online Users list and start chating...like following

Tuesday, June 10, 2014

How to keep jQuery UI Accordion collapsed by default?

You can do that by setting attribute -> "active: false".

    <script>
        $(function () {
            $("#accordion").accordion({
                collapsible: true,
                active: false 
            });
        });        
    </script>

How to increase Height of accordion 100% in JQuery?

100% means height should be expanded based on height of the content. You can do that by following way.

    <script>
        $(function () {
            $("#accordion").accordion({
                collapsible: true,
                heightStyle: "content"

            });
        });        
    </script>

Thursday, May 29, 2014

How to create MaskedTextBox custom control in Asp.net?

A Masked Textbox is very handy when you want to put a mask for "Phone, SSN or Date" Fields throughout the project. Especially, when you have many places in your project where you have to do masking on textboxes. Masking is useful because it prevents a user from entering wrong inputs. If we create custom control for Masking, it will be easier for us to just drag and drop control and apply masking format like
for U.S. Phone-> (999) 999-9999 where 9 represents digit only. So the question is how to create a custom control... and here it is:

You can do this by JQuery and VB/C# class. You need two files of JQuery:
1. jquery-1.9.1.min.js
2. jquery.maskedinput.min.js
You can download these two files from :
http://jquery.com/
http://digitalbush.com/projects/masked-input-plugin/

And one VB/C# Class file. Following is the VB.net code:

Public Class MaskedTextBox
    Inherits TextBox


    Private _cMast As String
    Public Property cMask() As String
        Get
            Return _cMast
        End Get
        Set(ByVal value As String)
            _cMast = value
        End Set
    End Property


    Private Sub MaskedTextBox_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim scriptText As String



        scriptText = "<script src="jquery-1.9.1.min.js"></script>" _
            + "<script src="jquery.maskedinput.min.js"></script>" _
            + "<script>$(document).ready(function() {" _
            + "$('#" + Me.ID + "').mask('" + cMask + "');" _
            + "$('#" + Me.ID + "').click(function () { " _
            + "if (document.getElementById('" + Me.ID + "').value == '" + cMask.Replace("9", "_") + "') {" _
            + "setCaretPosition('" + Me.ID + "', 0) }" _
            + "});" _
            + "});</script>"



        Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), _
            Me.ID + "t", scriptText)

        scriptText = "<script>function setCaretPosition(elemId, caretPos) { " _
            + "var el = document.getElementById(elemId);" _
            + "el.value = el.value;" _
            + "if (el !== null) {" _
            + "if (el.createTextRange) {" _
            + "var range = el.createTextRange();" _
            + "range.move('character', caretPos);" _
            + "range.select();" _
            + "return true;}" _
            + "else {" _
            + "if (el.selectionStart || el.selectionStart === 0) {" _
            + "el.focus();" _
            + "el.setSelectionRange(caretPos, caretPos);" _
            + "return true;}" _
            + "else {" _
            + "el.focus();" _
            + "return false;}}}}</script>"


        Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), _
            "setCursor", scriptText)


    End Sub
End Class

Once you create this class file in your project. you have to register this control wherever you want to use. you can register it either on the page or in web.config if you want to use throughout the project.

For web.config:
<configuration>

  <system.web>
    
    <pages>
      <controls>
         <add assembly="CustomControls" namespace="CustomControls" tagprefix="cc">
      </add>
    </controls>
    </pages>

  </system.web>
</configuration> 


For .aspx page:
<%@ Register TagPrefix="cc" Namespace="CustomControls" Assembly="CustomControls" %>

Complete .aspx page code:
<%@ Page Language="vb" AutoEventWireup="false" 
    CodeBehind="Default.aspx.vb" Inherits="CustomControls.WebForm1" %>

<%@ Register TagPrefix="cc" Namespace="CustomControls" Assembly="CustomControls" %>
   
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>MaskedTextBox<title/>
</head> 
<body> 
<form id="form1" runat="server"> 

U.S. Phone: 
<cc:MaskedTextBox ID="mtxtPhone" runat="server" 
 cMask="(999) 999-9999" /> 
U.S. Phone: 
<cc:MaskedTextBox ID="mtxtPhone1" runat="server"
 cMask="(999) 999-9999" />  
SSN 1: 
<cc:MaskedTextBox ID="mtxtSSN" runat="server"
 cMask="999-99-9999" /> 
SSN 2: 
<cc:MaskedTextBox ID="mtxtSSN1" runat="server"
 cMask="999-99-9999" /> 

</form> 
</body> 
</html> 


Final Result and sample project structure will look like this:

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...