Getting values of CheckBoxList items from javascript

On my last post I wrote on getting CheckBox values from the client side.

On the same project, I needed the same functionality for the CheckBoxList control.
Because CheckBoxList holds ListItem I couldn’t access the InputAtributes property of the CheckBox.
After some googling I found this post by Evan Freeman that explains how to create a new custom control that renders the server side values into the HTML code.
In this way, you gain server side and client side functionality at the same time.

This is the code for the new ChcekBoxList control:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Security.Permissions;

namespace System.Web.UI.WebControls{
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.LinkDemand,
Level = AspNetHostingPermissionLevel.Minimal),
ToolboxData("")]
public class CheckBoxListWithClientValues : CheckBoxList
{
private CheckBox _controlToRepeat;
private bool _cachedIsEnabled;
private bool _cachedRegisterEnabled;

public CheckBoxListWithClientValues()
{
    this._controlToRepeat = new CheckBox();
    this._controlToRepeat.EnableViewState = false;
    this._controlToRepeat.ID = "0";
    this.Controls.Add(this._controlToRepeat);
}         

protected override void RenderItem(ListItemType itemType,
    int repeatIndex,
    RepeatInfo repeatInfo,
    System.Web.UI.HtmlTextWriter writer)
{   
    if (repeatIndex == 0)
    {     
        this._cachedIsEnabled = base.IsEnabled;
        this._cachedRegisterEnabled = ((this.Page != null) && base.IsEnabled);
    }               

    ListItem item = this.Items[repeatIndex];
    this._controlToRepeat.Attributes.Clear();

    if (item.Attributes.Count > 0) //has attributes  
    {       
        foreach (string str in item.Attributes.Keys)
        {          
            this._controlToRepeat.Attributes[str] = item.Attributes[str];
        } 
    }
    this._controlToRepeat.ID = repeatIndex.ToString(NumberFormatInfo.InvariantInfo);
    this._controlToRepeat.Text = item.Text;  
    this._controlToRepeat.Checked = item.Selected;
    this._controlToRepeat.EnableViewState = true;
    this._controlToRepeat.Enabled = this._cachedIsEnabled && item.Enabled;
    this._controlToRepeat.InputAttributes.Add("value", item.Value); //add the value attribute to be rendered
    this._controlToRepeat.RenderControl(writer);
}
}
}

And thanks for Evan for posting this code.

Happy coding.
Netanel.

ASP.NET Get a CheckBox value from javascript

Recently I needed to access the value of a CheckBox from javascript.

Because CheckBox doesn’t have a Value property I tried the following:
myCheckBox.Attributed.Add("value", "test");
And tried to access it from javacstipt:
alert($("myCheckBox").value)
I was surprised to find out that the message in the alert was “on” and not “test” as I expected so I looked at the source of the page and this is what I saw:

As you can see the value I set on the server side code doesn’t appear in the result html code.
After a little more research I found out there is a property for the CheckBox that is called “InputAttributes” – this property adds the attributes to the CheckBox input.
This is the correct code:
myCheckBox.InputAttributes.Add("value", "test");
That’s all I needed.
Happy coding.
Netanel

ASP.NET calling a web service from javascript

Calling a web service from javascript should be a very easy task.
Especially if you are using prototype or jquery in your project.

The other day I spent to much time trying to call a WebService using Prototype js library so I decided to post the code here in case anyone else encounter the same problem.
Server side code:
            [WebService]
            [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
            [System.Web.Script.Services.ScriptService]
            public class WebService : System.Web.Services.WebService
            {
                [WebMethod]
                public string HelloWorld(string testParam)
                {
                    return testParam;
                }
            }
Prototype syntax:
            new Ajax.Request('WebServices/WebService.asmx/HelloWorld',
                {
                postBody: "{testParam:'hello'}",
                method: 'post',
                contentType: 'application/json; charset=utf-8',
                onSuccess: function(transport) {
                    alert(transport.responseText);
                    },
                onFailure: function(transport) {
                    alert(transport.responseText);
                    }
            });
JQuery syntax:
            $.ajax({
                    type: "POST",
                    url: "WebServices/WebService.asmx/HelloWorld",
                    data: "{testParam:'hello'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(result){
                        alert(result.d);
                    }
                });
That’s it.
Hope it help someone out
there.
Happy coding!
Netanel