CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Populating RadioButtonList Using jQuery, JSON in ASP.Net

By Satheesh Babu
Posted On Jun 19,2009
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 13
Category: jQuery
Print this article.

Populating RadioButtonList Using jQuery, JSON in ASP.Net

 

One of my previous article Building Cascading DropDownList in ASP.Net Using jQuery and JSON discussed about constructing cascading DropDownList control using jQuery and JSON. One of the user [Shah] has commented that his requirement was to populate a RadioButtonList instead of a child DropDownList control. Building a RadioButtonList in client side is not a straight forward task like DropDownList control due to the way it renders to the client side.

In my previous article, we have populated the child DropDownList [City] based on the selection in the parent DropDownList [State] using jQuery and AJAX. Moving forward, we will implement the same example by populating a RadioButtonList instead of a child DropDownList control.

 

Refer the below figure,

CasdingRB.png

 

Before moving into the article, it will be good if we understand how the ASP.Net RadioButtonList control will render to the client.

 

ASP.Net RadioButtonList control

If we have a RadioButtonList control on the ASPX page, it will be rendered as a HTML table with INPUT tags for radio buttons.

Something like,

 

<table id="RadioButtonList1" border="0">

       <tr>

              <td><input id="RadioButtonList1_0" type="radio" name="RadioButtonList1" value="Bangalore" /><label for="RadioButtonList1_0">Bangalore</label></td>

       </tr><tr>

              <td><input id="RadioButtonList1_1" type="radio" name="RadioButtonList1" value="Mysore" /><label for="RadioButtonList1_1">Mysore</label></td>

       </tr>

</table>

 

One thing to notice is, if the RadioButtonList control does not have any ListItem item loaded then ASP.Net will not render any HTML for the control. Hence, a RadioButtonList control with no ListItem will render no HTML which makes it impossible to access or populate it from client side. But if we look into our requirement, we need to populate the RadioButtonList only if we select a value in parent DropDownList(This means, we will have no HTML output for RadioButtonList initially). Thus, it is not be possible to achive our requirement using ASP.Net RadioButtonList control from client side scripts. In the coming sections, we will see how this difficulty can be addressed with a possible work around.

 

How to overcome this drawback?

To overcome this drawback, we will construct HTML radio button control for each city and will group all the radio button with same name to behave as RadioButtonList control using jQuery.

Something like,

<INPUT id=RadioButton0 onclick=RecordCheck(this) type=radio value=1 name=City><LABEL for=RadioButton0>Chennai</LABEL>

<INPUT id=RadioButton1 onclick=RecordCheck(this) type=radio value=2 name=City><LABEL for=RadioButton1>Coimbatore</LABEL>

 

When the user clicks any option, we will record the value in an ASP.Net HiddenField control which then can be fetched in the server side. Thus, we can see onclick event configured for the radio buttons in the above code.

With this information, we will redo the sample application we did on the previous article with radio button control.

 

Steps

1.      Create a new Asp.Net project in your Visual Studio.

2.      Drag DropDownList control from the toolbox and rename its ID to ddlStates.

3.      For easy understanding and simplicity, I will hardcode the ListItems.  You can bind it from database in your case. This DropDownList will be the parent.

4.      Declare a DIV tag to populate the radio buttons from jQuery.

<DIV id="rdbList">           

</DIV>

5.      Drag an ASP.Net HiddenField control to record the city selection in the client side.

<asp:HiddenField ID="hfCity" runat="server"></asp:HiddenField>

 

We will include the same HttpHandler implementation we used in my previous article to return cities in JSON format.

To include new HttpHandler, Right click the project in solution and click “Add New Item”. Select “Generic Hanlder”. I have named it as LoadCities.ashx. The HttpHanlder should get the StateID as a query string parameter to fetch the cities from database.  Again, I have hard-coded the cities based on the state id for simplicity purpose. You can fetch it from database. Now, the cities should be returned back in JSON format from the HttpHandler.

 

<%@ WebHandler Language="C#" Class="LoadCities" %>

 

using System;

using System.Web;

using System.Text;

 

public class LoadCities : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

        string StateID = context.Request.QueryString["StateID"];       

        //Contact Database to get th elist of cities based on StateID

        StringBuilder strCities = new StringBuilder();

        if (StateID == "1")

        {

            strCities.Append("[");

 

            strCities.Append("{");

            strCities.Append("\"City\":\"Chennai\",");

            strCities.Append("\"ID\":\"1\"");

            strCities.Append("},");

 

            strCities.Append("{");

            strCities.Append("\"City\":\"Coimbatore\",");

            strCities.Append("\"ID\":\"2\"");

            strCities.Append("}");

 

            strCities.Append("]");

        }

        else if (StateID == "2")

        {

            strCities.Append("[");

 

            strCities.Append("{");

            strCities.Append("\"City\":\"Bangalore\",");

            strCities.Append("\"ID\":\"1\"");

            strCities.Append("},");

 

            strCities.Append("{");

            strCities.Append("\"City\":\"Belgaum\",");

            strCities.Append("\"ID\":\"2\"");

            strCities.Append("}");

 

            strCities.Append("]");

        }

        context.Response.ContentType = "application/json";

        context.Response.ContentEncoding = Encoding.UTF8;

        context.Response.Write(strCities.ToString());

        context.Response.End();

    }

    public bool IsReusable {

        get {

            return false;

        }

    }

}

 




I have only hard coded for 2 states, you can loop through the result set from database and give back the data in JSON format.

 

Calling HttpHanlder from jQuery and building RadioButtonList control

Read the following FAQ’s to integrate and use jQuery in Visual Studio 2008,

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

How to use jQuery intellisense in an external javascript file?

 

We will declare an onchange event for the parent DropDownList which will make the AJAX call to the server to fetch the JSON data.

Refer the below code,

 

<script src="_scripts/ jquery-1.3.2.min.js" type="text/javascript"></script>

    <script language="javascript">

        $(document).ready(function() {

            $("#ddlStates").change(function() {               

                $('#rdbList').html("");              

                var StateID = $("#ddlStates > option[selected]").attr("value");

                if (StateID != 0) {

                    $.getJSON('LoadCities.ashx?StateID=' + StateID, function(cities) {

                        var i = 0;

                        $.each(cities, function() {

                            var rdb = "<input id=RadioButton" + i + " onclick=RecordCheck(this) type=radio name=City value=" + this['ID'] + " /><label for=RadioButton" + i + ">" + this['City'] + "</label>";

                            $('#rdbList').append(rdb);                            

                            i++;

                        });                      

                    });

                }

            });

 

        });

        function RecordCheck(rdb) {          

            $('#hfCity').val(rdb.value);

        }

    </script>

The getJSON method will be called for every state selection except for the value of “select” in parent DropDownList. When the JSON result is returned it will call the call-back function(2nd argument of getJSON method) which will populate the RadioButtonList control inside the DIV tag.

The function RecordCheck() will be called once the user selects any city and the corresponding value will get recorded in the hidden field.

 

Accessing the selected Value

In serverside, we can get the city selected from the hidden field.

Refer below,

  protected void btnSave_Click(object sender, EventArgs e)

    {      

            Response.Write(hfCity.Value);

     }

 

Execute the page and see it in action.

 

One of the problems in this approach is, once we click save, the radio buttons we have populated through jQuery will not persist and will get cleared off from the form.

Refer the below figure,

aftersave.png

This is because; asp.net will maintain the page control’s state in viewstate which it uses to rebuild the control on every postback. Since, we are building the control in client side script asp.net will not have any information to render it back to the browser.

If you would like to retain the radio buttons and selection then we can include an ASP.Net RadioButtonList and can bind it in the save event. The city selection can be done again based on the value in HiddenField.

The final code will look like,

ASPX

<table>

        <tr>

        <td>State</td>

        <td>

            <asp:DropDownList ID="ddlStates" runat="server">

            <asp:ListItem Value="0">Select</asp:ListItem>

            <asp:ListItem Value="1">Tamil Nadu</asp:ListItem>

            <asp:ListItem Value="2">Karnataka</asp:ListItem>

            </asp:DropDownList>

        </td>

        </tr>        

        <tr>

        <td>Cities</td>

        <td>                  

          

            <DIV id="rdbList">

           

            </DIV>

            <asp:HiddenField ID="hfCity" runat="server"></asp:HiddenField>

            <asp:RadioButtonList ID="rdbCities" runat="server">

            </asp:RadioButtonList>

        </td>

        </tr>

        <tr>

        <td colspan="2">

            <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />

        </td>

        </tr>

        </table>

CodeBehind

  protected void btnSave_Click(object sender, EventArgs e)

    {

        if (rdbCities.Items.Count > 0 && hfCity.Value == "")

        {

            Response.Write(rdbCities.SelectedValue);

        }

        else

        {

            Response.Write(hfCity.Value);

            string StateId = ddlStates.SelectedValue;

            LoadCities(StateId);

            if (hfCity.Value != "")

            {

                rdbCities.Items.FindByValue(hfCity.Value).Selected = true;

                hfCity.Value = "";

            }

        }

   

    }

    public void LoadCities(string StateId)

    {

        if (StateId == "1")

        {

            rdbCities.Items.Clear();

            rdbCities.Items.Add(new ListItem("Chennai", "1"));

            rdbCities.Items.Add(new ListItem("Coimbatore", "2"));

        }

        else if (StateId == "2")

        {

            rdbCities.Items.Clear();

            rdbCities.Items.Add(new ListItem("Bangalore", "1"));

            rdbCities.Items.Add(new ListItem("Belgaum", "2"));

        }

      

    }    

 

Downloads

Download Source 

 

Conclusion

It is always a difficult task if we want to add a new item to an existing asp.net controls from client side scripts due to various reasons like viewstate, asp.net security model and the complexity when we use javascript. Thus, with this article we have identified an easy solution if we want to build RadioButtonList control (a workaround if we want to say it exactly) from client side scripting. Thanks to jQuery! Download the source attached with this article and see it in action!

Happy coding!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Thank you so much fo
Thank you so much for this arltcie, it saved me time! http://modlesd.com [url=http://cnifqwh.com]cnifqwh[/url] [link=http://zkyhvoijvq.com]zkyhvoijvq[/link]
Thank you so much fo
Thank you so much for this arltcie, it saved me time! http://modlesd.com [url=http://cnifqwh.com]cnifqwh[/url] [link=http://zkyhvoijvq.com]zkyhvoijvq[/link]
Thank you so much fo
Thank you so much for this arltcie, it saved me time! http://modlesd.com [url=http://cnifqwh.com]cnifqwh[/url] [link=http://zkyhvoijvq.com]zkyhvoijvq[/link]
Fell out of bed feel
Fell out of bed feeling down. This has brhtegenid my day!
Fell out of bed feel
Fell out of bed feeling down. This has brhtegenid my day!
Fell out of bed feel
Fell out of bed feeling down. This has brhtegenid my day!
Need help
Hi, I have download the sample project and test the page however when i am selecting state from the dropdown cities with radiobuttonlist are not coming. When i am clicking on button after that cities are coming. I am using VS 2010. I have also other question that can't we change the jquery file to newer version?
thanks!
your article helped me out a lot! Thank you very much!
RE:Server Calls
Thanks for the feedback! I can understand it is expensive but in realtime you may have large nummber of states for a country which can make your data bulk. I guess loadding whenever it is required will be the best, keeping in mind that the realtime user will not scroll between the states to find his state. :)
Yeah..you can decide this based on your scenario..
Server Calls
Isn't sending an individual call to the server for each state expensive? Is that better than wrapping the whole thing up as a states object and making one call?
RE:JavaScriptSerializer??
Hi Magnus,
You are correct!! The above technique can be used if you dont have .net 3.5/ASP.Net Ajax installed on your server!
Thanks!
JavaScriptSerializer??
You can use the JavaScriptSerializer to create the json.

http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

Code:

new JavaScriptSerializer().Serialize(new object[] { new { ID = 1, City = "Chennai" }, new { ID = 2, City = "Coimbatore" } });

Great work
This is really great. I just wanted to point out that it can easily be modified to populate a CheckBoxList instead of a RadioButtonList. I've been searching for a way to do this with a CheckBoxList for over a week and only found this incidentally via MS's blog feed.

All that really needs to be done is to replace this:

var rdb = "<input id=RadioButton" + i + " onclick=RecordCheck(this) type=radio name=City value=" + this['ID'] + " /><label for=RadioButton" + i + ">" + this['City'] + "</label>";

with this:

var rdb = "<input id=cblCities" + i + " onclick=RecordCheck(this) type=checkbox name=City value=" + this['ID'] + " /><label for=cblSurcharges" + i + ">" + this['City'] + "</label>";


And replace

<asp:RadioButtonList ID="rdbCities" runat="server"></asp:RadioButtonList>

with

<asp:CheckBoxList ID="cblCities" runat="server"></asp:CheckBoxList>


Since both the RadioButtonList and CheckBoxList are just containers for the ListItem object type you don't even need to change the code behind except to rename rdbCities to cblCities.

Thanks for all the work. It would be cool if you could include a section about how to do it as a CheckBoxList so that people searching specifically for that could find it.