【发布时间】:2012-12-10 13:01:14
【问题描述】:
我正在尝试使用PageMethodsbind a state ddl by onChange of country ddl
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'.
作为浏览器弹出窗口出现此错误。我在这里缺少什么?
解决方案
我认为这里的问题是 CS 和 JS 函数的同名 GetStates,我进行了更改并且它起作用了。
【问题讨论】:
-
不要做(字符串)行[“Id”]。而不是 Convert.ToString(row["Id"]) (和所有其他字段)或 row["Id"].ToString() 进行适当的空检查
-
@ManishMishra 没有同样的错误,我尝试了 x.toString() 和 convert.toString(x)
-
您是否正在向您的 GetStates 方法发送一个 int 数据?我的意思是你的 CountryId 是 int 吗?如果不是,请尝试将其更改为 int 或尝试将您的 GetStates 方法的参数类型更改为字符串 Cid,并在方法内将其转换为 int
-
@ManishMishra 其调用形式 JS 即 'var Countryid = e.options[e.selectedIndex].value;' ,那么我应该将它转换为 int 然后通过吗?
-
是的,你可以这样做,这样做。 var Countryid= parseInt(e.options[e.selectedIndex].value)
标签: c# javascript asp.net drop-down-menu pagemethods