2

我有 hiddentfield 其值在 javascript 上发生变化。

我只是想在隐藏字段的值从 javascript 更改时触发服务器端事件 valuechanged 事件。

我试过:

__doPostBack('hfLatitude', 'ValueChanged');

但是给我错误:

Microsoft JScript runtime error: '__doPostBack' is undefined

还有其他选择吗?

请帮我。

4

3 回答 3

4

在 javascript 中,隐藏元素的值更改不会自动触发“onchange”事件。因此,您必须使用“GetPostBackEventReference”手动触发已在回发时执行的代码。

因此,使用经典的 javascript 方法,您的代码应该类似于下面的示例。

在您的 aspx/ascx 文件中:

    <asp:HiddenField runat="server" ID="hID" OnValueChanged="hID_ValueChanged" Value="Old Value" />
    <asp:Literal runat="server" ID="litMessage"></asp:Literal>
    <asp:Button runat="server" ID="btnClientChage" Text="Change hidden value" OnClientClick="ChangeValue(); return false;" />

    <script language="javascript" type="text/javascript">

        function ChangeValue()
        {
            document.getElementById("<%=hID.ClientID%>").value = "New Value";
            // you have to add the line below, because the last line of the js code at the bottom doesn't work
            fValueChanged();
        }

        function fValueChanged()
        {
            <%=this.Page.GetPostBackEventReference(hID, "")%>;
        }

        // the line below doesn't work, this is why you need to manually trigger the fValueChanged methiod
        // document.getElementById("<%=hID.ClientID%>").onchange = fValueChanged;

    </script>

在您的 cs 文件中:

protected void hID_ValueChanged(object sender, EventArgs e)
{
    litMessage.Text = @"Changed to '" + hID.Value + @"'";
}
于 2013-11-04T15:33:55.810 回答
1

又快又脏:

只需在表单上放置一个 asp 按钮。设置它display:none

<asp:Button id="xyx" runat="server" style="display:none" OnClick="xyx_Click" />

在其单击事件上调用任何服务器端事件。

protected void xyx_Click(o,e)
{
   //you server side statements
}

要从 JS 调用它,请使用如下:

<script>

function myserverside_call()
{
var o = document.getElementById('<%=xyx.ClientID%>');
o.click();
}

function anyotherjsfunc()
{
   //some statements
   myserverside_call();
}
</script>
于 2013-11-01T11:21:25.913 回答
1

第一种方法是使用HiddenField.ValueChanged Event

如果您还想在客户端查看此变量,请使用以下命令:

    $('#hidden_input').change(function() { 
     alert('value changed');
});

第二种方法是给变量赋值:

$('#hidden_input').val('new_value').trigger('change');
于 2013-11-01T11:14:05.563 回答