我正在尝试bind a state ddl by onChange of country ddl
使用PageMethods
aspx中的JS代码
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代码
[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;
}
错误消息
The server method 'GetStates' failed with the following error: System.InvalidCastException-- Unable to cast object of type 'System.Int32' to type 'System.String'.
我将此错误视为浏览器PopUp。我在这里错过了什么?
解
我认为这个问题与CS和JS函数同名的GetStates,我改变了它并且有效。
答案 0 :(得分:0)
我认为问题在于
foreach (DataRow row in dstFillState.Tables[0].Rows) // Loop over the rows.
{
strHTML = strHTML + "<option value=" + (string)row["Id"] +">" + (string)row["State"] +"</option>";
}
你应该像这样使用
foreach (DataRow row in dstFillState.Tables[0].Rows) // Loop over the rows.
{
strHTML = strHTML + "<option value='" +row["Id"].ToString() +"'>" + row["State"].ToString() +"</option>";
}
甚至
foreach (DataRow row in dstFillState.Tables[0].Rows) // Loop over the rows.
{
strHTML = strHTML + "<option value='" + row["Id"] +"'>" + row["State"] +"</option>";
}