Bind a CheckBox list from database using jQuery AJAX

Hi All,

I have seen many questions in the forums that how can we bind the CheckBox list from the database via Ajax. There could be many ways to do in an ASP.NET but I will be using the one of the most efficient options available .

In this post, I’ll be using jQuery Ajax to get the data from the server (that will be fetch the data from database) and then will create the CheckBox list dynamically.

Continue reading

Advertisement

How to consume wcf service using JavaScript Proxy

Hello All,

Today I am going to discuss one another great feature of WCF. Do you know that a WCF service allows us to create a JavaScript Proxy?

Yes it does!!

But let’s first understand that what is a proxy? As we already know whenever we have to use any web service or WCF service, we need to create proxy of that service and with the help of proxy, we use the functionalists provided by the web/WCF service.  Proxy acts a intermediary between the client of the service and the actual service. Proxy provides a simple interface to the consumer of service and all the intricacies like creating a connection, creating and sending the request, getting the response etc is handled by the proxy itself.

Continue reading

Presented on ASP.NET MVC and AJAX at C# Corner Delhi Chapter event

Hi All,

Again we had a very successful event at C# Corner Delhi Chapter July meet on 20the July. This time again despite bad weather, it was attended by more that 100 attendees and we discussed a list of hot technologies. This time Mahesh Chand sir, the founder of C# Corner was also present and discussed about Enterprise architecture.

Continue reading

document.ready vs Javascript onload

It is a small post, who are new to jQuery or just started working with jQuery. As we all know that jQuery is Client side library and provides a wrapper over JavaScript . One of the very good things about jQuery that it runs seamlessly in all leading browsers while you must have faced many issues related to the browsers when you work with JavaScript.

So let’s jump to the topic. What is the difference between let’s first go by an example.

I have created a simple default.aspx page in my asp.net empty application and added few images and put the path from web and added few text. Now I put a general alert and called it on load method of window as

<script type="text/javascript" language="javascript">
        window.onload = OnLoad();
        function OnLoad() {
            alert('I am called by window.onload');
        }
    </script>

Now again I tried to change the code to jQuery document.ready function. And used the code as

$(document).ready(function () {
              OnLoad();
         });
        function OnLoad() {
            alert('I am called by document.ready');
        }

and when I ran it. I got the alert very fast. So what I wanted to point out here that jQuery’s document.ready runs much earlier the JavaScript onload. Why?

document.ready get’s fired as soon as DOM is ready and registered with the browser. It does not wait for the all the resources to get loaded. It allows us some very cool showing, hiding and other effects as soon as user sees the first element on the page.

While Javascript’s onload method gets fired only when all content of the webpage and image, iframes etc get loaded in browser then onload get’s fired.

So do we have a method in JavaScript that works in similar way as document.ready?

Partially yes.

We have a method called DOMContentLoaded  that is actually called by jQuery from document.ready. But that’s not it.  DOMContentLoaded is not available to every browser and versions. For IE > 9,  onreadystatechange works in the same way. In case nothing works in browser, jQuery has a fallback and it implemented own logic to traverse the DOM and check the when the DOM got registered and fires document.ready accordingly.

So I hope you all got to know the basic difference between these two.

Cheers,
Brij

HTML5 : Set multiple audio/video files dynamically and run one by one

One of my blog Reader was working on HTML5 audio controls. He asked me a question How can he play multiple audio files one by one. And his requirement was to set the audio files dynamically. So I thought of sharing the solution here. You can customize based on your requirement.

So what I have done. I created an audio control as

 <audio id="ctrlaudio" controls="controls" runat="server">
                Your browser does not support the audio tag.
 </audio>

As you can see an Audio control and made it as runat server, So that I can set some values from code behind. I have also created a hidden variable to set the comma separated name of songs that I want to run one by one. In my code behind I am setting a source for this audio control. My code behind as

string innerHTML =
            "<source src='song1.mp3'></source>";
        ctrlaudio.InnerHtml = innerHTML;
        hdnSongNames.Value = "song1.mp3" + "," + "song2.mp3";

So the whole logic is written in JavaScript and I have used jQuery as well. The logic is something like, First get the list of song names using hidden variable that I require to run one by one . Then I attached an event ended to the audio control. This event is fired when the current playing song is ended. And when one song ended and other next song starts playing. Let’s see the code

 $(function () {
            //Find the audio control on the page
            var audio = document.getElementById('ctrlaudio');
            //songNames holds the comma separated name of songs
            var songNames = document.getElementById('hdnSongNames').value;
            var lstsongNames = songNames.split(',');
            var curPlaying = 0;
            // Attaches an event ended and it gets fired when current playing song get ended
            audio.addEventListener('ended', function() {
                var urls = audio.getElementsByTagName('source');
                // Checks whether last song is already run
                if (urls[0].src.indexOf(lstsongNames[lstsongNames.length - 1]) == -1) {
                    //replaces the src of audio song to the next song from the list
                    urls[0].src = urls[0].src.replace(lstsongNames[curPlaying], lstsongNames[++curPlaying]);
                    //Loads the audio song
                    audio.load();
                    //Plays the audio song
                    audio.play();
                    }
            });
        });

As I have made a comment on most lines of the code, I don’t need to explain it again here. One point, I want to make it here that I have done some coding at Code behind you can totally do at Client side only. If you need any details from server, can initiate a Ajax call get the details (here list of songs) .

Also, the video tag also works similar to audio tag. So you can work similarly with video tag also.

So you can use your business logic.

[Update] Some of my blog reader asked about hdnSongNames. Let me make it bit more clear.

In second paragraph I have written “I have also created a hidden variable to set the comma separated name of songs that I want to run one by one.” So this bold hidden variable is hdnSongNames and I used an asp.net hidden field with Id hdnSongNames (The aspx part is not shown in the post). This field, I have used to access some server side values at client side. If you see in my second code snippet (which is a server side C# code), I have assigned some song names at code behind and used the same field in my third code JS code snippet to read the song names. Hope it clarifies.
Hope you all have enjoyed this.

Cheers,
Brij

Playing with List Controls using jQuery

You all must be knowing, I am fan of jQuery. The kind of neat and clean code and the power provided by jQuery at Client side scripting is unmatchable.

List Controls are one of the most used form controls. And we all know that manipulating these controls from JavaScript always have been a tough task.

In this post I’ll be discussing about accessing List controls and manipulating it with the help of jQuery. Hope you all like it and also will able to apply with other controls as well.

Continue reading

Error While Serailize/De-Serailize DateTime in JSON format : A Solution

Sometimes back, I was working on one my modules in my application. Here I had an of a Class which has some properties of DateTime type. Actually I was serializing the object using JavaScriptSerializer to serialize it in JSON format but later could not be able to deserialize it again.

So I thought of digging deep to this problem. So  I will be discussing it with an example. Let’s have a class Continue reading…

Call HTTPhandler from jQuery, Pass data and retrieve in JSON format

Download sample for here

Last few days ago, I was woking with HTTP handler. Here I was required to call handler from Client script. Later I found, that I need to pass some data to handler and also recieve some from it.

So I was looking for if there is some way we can pass some data to handler in some format and can recieve.

So Here I am going to share, How we can call a HTTPHandler from jQuery and can pass some data to handler and receive as well.

So Let’s go step by step Continue reading…

Why MaxLength property of a textbox with multiline mode doesn’t work? A Solution

Many developers set the MaxLength property of a Textbox and it works fine until the Textbox is not in multiline mode, which is by default behavior of a Textbox.

So what is the basic diffference between a textbox in single line and multiline mode!!!

Let’s see, how it gets rendered as html. Lets have a look

Textbox with SingleLine mode

Textbox with SingleLine mode

Now Textbox with MultiLine mode

Textbox with MultiLine mode

Textbox with MultiLine mode

As you can see, When a Textbox is in SingleLine mode, it gets rendered as a input type text  and when it is in MultiLine mode, it gets rendered as a textarea. As we know MaxLength property works only for input type.

So what is the solution. We need to have a custom solution for this.

Let’s try some solution,

One thing we can do, we can attach a function on onkeypress event to the textbox, which first check the length of input string and if exceed with limit it just returns else allow to enter any input. In the below example I have used the maximum length as 10.

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" onkeypress="return CheckLength();"></asp:TextBox>

//And the javascript code is
function CheckLength() {
            var textbox = document.getElementById("<%=tb.ClientID%>").value;
            if (textbox.trim().length >= 10) {
                return false;
            }
            else {
                return true;
            }
        }

This works fine until, a user doesn’t paste a text  which is greater than the max length that is given( here 10).  So there is no simple way to stop this. To overcome this problem, one should use one of the asp.net validators.

One can go for the custom validator, and provide a javascript function, which checks the length of the text and if exceeds the maxlength then show an error. Let’s see the code below

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" ></asp:TextBox>
//Validator
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter maximum 10 charachters." ControlToValidate="tb"
         SetFocusOnError="true" ClientValidationFunction="CheckMaxLength" ></asp:CustomValidator>

//Client Validator function
function CheckMaxLength(sender, args) {
            if (args.Value.trim().length >= 10) {
                args.IsValid = false;
            }
        }

But there is another smart way is there, to acheive this. We can also use Regular expression validator for this, which will check the count of the entered character and will throw an error if it exceeds. Here we would not require to write a javascript function. We need to have a regular expression that will work. Let’s see the code

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" ></asp:TextBox>

//Regular Expression validator
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="tb" ErrorMessage="Please enter maximum 10 charachters."
 SetFocusOnError="true" ValidationExpression="^[a-zA-Z.]{0,10}$"></asp:RegularExpressionValidator>

Here we don’t require to write a javascript function. I have used a regular expression ^[a-zA-Z.]{0,10}$, which allows all the characters with length 0 to 10.

Hope you all must have enjoyed.

Thanks,

Brij

 

Javascript Dictionary

Might be some of you already know about Dictionaries in JavaScript. But recently I, worked on JavaScript dictionary. And that was really interesting and helpful for me. So I wanted to share my findings to you all. Please share your feedback for my posting.

JavaScript provides us a way to make a Dictionary object and use it as a C# dictionary. Although we would not be having all the properties that is supported by C# dictionary, but we will be able to use it as a normal dictionary i.e. in key value format.

Let’s see one simple example:

I have stored list of all week days as keys and assigned some numbers to these as values. Let’s see the code.

function CreateDayDictionary() {
var days = new Array();
days['Sunday'] = 1;
days['Monday'] = 2;
days['Tuesday'] = 3;
days['Wednesday'] = 4;
days['Thursday'] = 5;
days['Friday'] = 6;
days['Saterday'] = 7;
}

Now to fetch the values at any point of time, we can fetch as per the code given below. Here I have made a function to alert some data. It can be as

 function ShowDays() {
        alert(days['Sunday']);
        alert(days['Thursday']);
        alert(days['Saterday']);
    }

It will show three alerts, first 1 then 5 and lastly 7.

So we can store some global data in our page. And this data we can access, at different events, we require.

Similarly we can store objects in the dictionary in same way. Let’s see the code

 function CreateDictionarywithObject() {
        var objDictionary = new Array();
        // Creating a dictionary which is holding five objects
        for (var i = 0; i < 5; i++) {

            var obj= new myClass();
            obj.member1 = 'member1data' + i;
            obj.member2 = 'member2data' + i;
            obj.member3 = 'member3data' + i;

            objDictionary['Obj' + i] = obj;
        }
        //Fetching third Object
        var fetchedObj = objDictionary['Obj3'];
        alert(fetchedObj.member1);
        alert(fetchedObj.member2);
        alert(fetchedObj.member3);

    }

Now, one more thing if you want to pass the data from server to client as a JSON data, you can serialize a C# dictionary at server side, and again when you will desterilize at client side you will be getting the dictionary as we discussed above. Let’s see the magic.

Here I have made one class Employee as

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public int Age { get; set; }
}

Now, on the page load, I created a dictionary with some data, like below

List<Employee> employees= new List<Employee>()
        {
            new Employee{ Id=1000, Name="Brij", Age=27, Salary=800000},
            new Employee {Id=1001, Name = "Rahul", Age=28,Salary=500000},
            new Employee {Id=1002, Name = "Anoop", Age= 29 ,Salary = 60000}
        };
Dictionary<string, Employee> employeeData = employees.ToDictionary(em => em.Id.ToString(), emp => emp);

Now serialize the data using JavaScriptSerializer and assigned it in a hidden variable

JavaScriptSerializer ser = new JavaScriptSerializer();

hfData.Value = ser.Serialize(employeeData);

Now I have a textbox and a button to show employee details. My aspx code looks like this

<body>
    <form id="form1" runat="server">
    <div>
        <span>Id: </span> &nbsp;<input id="idName" type="text" /><br  />
        <input id="Button2" type="button" value="Displaydetail" onclick="show();"/>
        <asp:HiddenField ID="hfData" runat="server" />
    </div>
    </form>
</body>

Here I will be entering the Id of the employee, and on clicking the button “Show details”, I am displaying the data as JavaScript alerts. So let’s see the JavaScript code

function parseEmployeeData() {
        //for parsing the data
        employees = JSON.parse(document.getElementById("<%= hfData.ClientID%>").value);

    }

    function show() {
        parseEmployeeData();
        var key = document.getElementById('idName').value;
        var emp = employees[key];
        if (typeof (emp) != 'undefined') {
        // If key is found then dispaly the details
            alert(emp.Name);
            alert(emp.Age);
            alert(emp.Salary);
        }
        else {
        // key not found
            alert('No data found');
        }
    }

As you can see, first I am parsing the data using JSON, and then finding the value in the dictionary using some key and displaying the details as a JavaScript alert.
This sample is just for an example, to show how we can use JavaScript dictionary in our daily life.

Here, I have used namespace System.Web.Script.Serialization for serializing the data at C#. Also, I have included JSON JavaScript file in my application to parse the data at Client Side.

Happy Client Scripting

Thanks,

Brij