HiddenField在后面的代码中显示为空白

时间:2016-10-10 15:53:49

标签: javascript c# jquery asp.net gridview

我有一个gridview,其中此网格的信息由文本框输入。然后,我单击一个保存按钮,此信息将保存到网格中。 对于其中一个文本框,它会显示一个菜单。用户从菜单中选择一个债权人,债权人ID保存在HiddenField中。

<td class="tblAddDetail" style="border-right:2px">
   <a style="float:left;width:16px;height:16px;margin-right:0px;left:0px;top:1px" title="Pick from list..." class="iconSearch" id="btnAddDetailCreditor"></a>
   <asp:HiddenField ID="hfCreditorID" runat="server"  />
   <input type="text" id="txtAddEditCreditorCode" class="lookuppopup" onblur="CheckCreditorAccountDetail(this.value)" style="text-transform:uppercase;width:80px" runat="server"/>
 </td> 

当用户从列表中选择一个债权人时,此功能会运行,该功能会使用名称和带有ID的HiddenField填充文本框:

function CheckCreditorAccountDetail(AC) {
            //AJAX Save
            if ($.trim(AC).length) {
                PageMethods.GetCreditorAccountCode(AC,
                                            OnCheckCreditorDetail,
                                            null
                                            );
            }
        }

 function OnCheckCreditorDetail(result) {
 $('#<%= hfCreditorID.ClientID %>').val(result.ID);
            $('#<%= txtAddEditCreditorCode.ClientID %>').val(result.AccountCode);
}

它调用WebMethod来查找数据库中的债权人:

[WebMethod]
    public static Creditor GetCreditorAccountCode(string AccountCode)
    {
        try
        {
            Creditor c = new Creditor(AccountCode);
            return c;
        }
        catch (Exception ex)
        {
            return new Creditor();
        }
    }

如果WebMethod返回一个值,则会填充隐藏字段和文本框。所以result是债权人,而result.AccountCode则给予债权人账户代码等。

但是当我尝试在后面的代码中调用这个HiddenField时,它总是空白的:

if (!int.TryParse(hfCreditorID.Value, out tmpCredID))
{
    valid = false;
}

问题是,当我点击保存按钮时会导致回发,所以我丢失了所有值。这不是隐藏的领域正在失去其价值,文本框也变回空白

1 个答案:

答案 0 :(得分:0)

看起来你正在混合/试图混合javascript和C#中使用的代码。

您正在发送result(正如Andrei已经指出的那样是javascript中的字符串)并尝试访问不存在的属性。 result.AccountCode

您的javascript函数名称与CheckCreditorAccountDetailOnCheckCreditorDetail不匹配。

如果您可以直接从代码中的TextBox获取值,为什么使用HiddenField? 有关工作示例,请参阅我的代码段。

在.aspx页面上:

<asp:HiddenField ID="hfCreditorID" runat="server" />
<asp:TextBox ID="txtAddEditCreditorCode" runat="server" onblur="OnCheckCreditorDetail(this.value)"></asp:TextBox>

<script type="text/javascript">
    function OnCheckCreditorDetail(result) {
        $('#<%= hfCreditorID.ClientID %>').val(result);
     }
</script>

在代码背后:

    protected void Button1_Click(object sender, EventArgs e)
    {
        txtAddEditCreditorCode.Text = hfCreditorID.Value + " - OK";
        //or just get the values from the TextBox without a HiddenField
        txtAddEditCreditorCode.Text = txtAddEditCreditorCode.Text + " - OK";
    }
相关问题