I am trying to bind a state ddl by onChange of country ddl
using PageMethods
JS Codes in aspx
function GetStates() {
var e = document.getElementById("<%=ddlCountry.ClientID %>");
var Countryid = e.options[e.selectedIndex].value;
PageMethods.GetStates(Countryid,ShowStates);
}
function ShowStates(results)
{
document.getElementById("li2").innerHTML=results;
}
.CS Codes
[System.Web.Services.WebMethod]
public static string GetStates(int Cid)
{
DataSet dstFillState = Tbl_State.FillDDLState(Cid);
string strHTML = "<select id='ddlState' name='ddlState'>";
foreach (DataRow row in dstFillState.Tables[0].Rows) // Loop over the rows.
{
strHTML = strHTML + "<option value=" + (string)row["Id"] +">" + (string)row["State"] +"</option>";
}
strHTML = strHTML + "</select>";
return strHTML;
}
ERROR Msg
The server method 'GetStates' failed with the following error: System.InvalidCastException-- Unable to cast object of type 'System.Int32' to type 'System.String'.
I get this error as a browser PopUp.What am I missing here ?
SOLUTION
Here problem i think was same name GetStates for both CS and JS functions,I altered and it worked.
I think the problem is in the line
foreach (DataRow row in dstFillState.Tables[0].Rows) // Loop over the rows.
{
strHTML = strHTML + "<option value=" + (string)row["Id"] +">" + (string)row["State"] +"</option>";
}
you should use like this
foreach (DataRow row in dstFillState.Tables[0].Rows) // Loop over the rows.
{
strHTML = strHTML + "<option value='" +row["Id"].ToString() +"'>" + row["State"].ToString() +"</option>";
}
or even
foreach (DataRow row in dstFillState.Tables[0].Rows) // Loop over the rows.
{
strHTML = strHTML + "<option value='" + row["Id"] +"'>" + row["State"] +"</option>";
}
here is a good example
Invalid postback or callback argument. When dropdown list populated with jquery and there is a postback