Thursday, November 25, 2010

Adding ListItem using JavaScript in ASP.NET

Sometimes we may need to add a listitem in a dropdownlist in client side using JavaScript. To add it we can use the following code. You can execute the cs code by any method or button click event etc.

In the test.aspx page





In the test.aspx.cs file
string jsCmdAddListItem = "var ddlTest = document.getElementById('" + drpTest.ClientID + "');" +
" var newListItem = document.createElement('OPTION');" +
" newListItem.text='ADDED_JS ITEM THREE';" +
" newListItem.value='3';" +
" ddlTest.appendChild(newListItem);";
if (!ClientScript.IsClientScriptBlockRegistered("ClientScript"))
{
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "ClientScript", jsCmdAddListItem, true);
}

Note that, the server side code knows nothing about this additional item. To let server side code know about this additional item you have to add a listitem as well to the DropDownList, for example:
ListItem itemThree = new ListItem("ADDED_CS ITEM THREE", "3");
drpTest.Items.Add(itemThree);

I'm afraid somebody will not understand it clearly, please leave a comment, I'll try to reply as early as possible.

No comments: