[英]Fire Serverside event from javascript
我有hiddentfield,其值在javascript上正在更改。
当它的值从javascript更改时,我只想触发hiddenfield的服务器端事件valuechanged事件。
我尝试了:
__doPostBack('hfLatitude', 'ValueChanged');
但是给我错误:
Microsoft JScript runtime error: '__doPostBack' is undefined
还有其他选择吗?
请帮我。
在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 + @"'";
}
第一种方法是使用HiddenField.ValueChanged Event 。
如果您还想在客户端观看此变量,请使用以下命令:
$('#hidden_input').change(function() {
alert('value changed');
});
第二种方法是为变量赋值:
$('#hidden_input').val('new_value').trigger('change');
快速与肮脏:
只需在窗体上放置一个asp按钮。 将其设置为display:none
。
<asp:Button id="xyx" runat="server" style="display:none" OnClick="xyx_Click" />
在其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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.