【问题标题】:Bind DropDownList with client side JS PageMethods将 DropDownList 与客户端 JS PageMethods 绑定
【发布时间】: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


【解决方案1】:

我认为问题出在一行

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>";
}

这是一个很好的例子
Invalid postback or callback argument. When dropdown list populated with jquery and there is a postback

【讨论】:

  • 没有同样的错误,我试过 x.toString() 和 convert.toString(x)
  • 还有其他问题。不在这一行。
  • 检查这个函数 'Tbl_State.FillDDLState(Cid)' 它需要一个字符串还是整数
  • 你可以放断点看看。结果来自哪里并不重要。只需在带有所选值的函数调用之前发出警报,然后查看从 java 脚本传递的值。并在服务器端代码上放一个断点,看看你得到了什么价值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 2011-07-25
相关资源
最近更新 更多