我在页面上有一个提交按钮。
<asp:Button ID="btnSubmit" runat="server" Text="Save Test" OnClick="btnSubmit_Click"
OnClientClick="return ValidateSaveTest(this);" />
在Javascript上,调用ValidateSaveTest函数验证所有字段。
function ValidateSaveTest(Sender) {
//do some validation, if fails return false from here. else move forward
var parameters = {};
parameters["parametersName"] = $("#" + hidTestId).val();
var succeededAjaxFn = function(result) {
if (result== true) {
var isNewVersion = confirm("Confirmation message");
if(isNewVersion)
{
//Raise server side button click event. Dont call click side event anymore.
$("#" + "<%=btnSubmit.ClientID %>").click();
}
return false;
}
}
var failedAjaxFn = function(result) { return false; }
//jquery ajax call
CallWebMethod("../Service.asmx", "IsTestUsed", parameters, succeededAjaxFn, failedAjaxFn);
//async call, always return false hence no postback from here.
//Need waiting unless ajax response is obtained.
return false;
}
收到ajax响应后,我需要从javascript中提升服务器端按钮点击事件。
答案 0 :(得分:14)
您可以从ClientScriptManager的GetPostBackEventReference方法获取所需的JavaScript代码:
返回可在客户端事件中使用以引发回发的字符串 到服务器。
这通常用于在<asp:linkButton>
之类的控件上编写onclick属性,但您也可以在jQuery回调中使用它:
var succeededAjaxFn = function(result) {
//Raise server side button click event. Dont call click side event anymore.
<%= Page.ClientScript.GetPostBackEventReference(btnSubmit, String.Empty) %>;
}
上面的<%= %>
块会为您写出以下JavaScript:
__doPostBack('btnSubmit','')
反过来,它会以一种ASP.NET认为单击按钮的方式将表单发回服务器,从而触发服务器端btnSubmit_Click
。
请注意,使用此方法,您可以将C#引用传递给实际控件。您无需担心其客户端ID,或__doPostback()
JavaScript函数的正确名称和参数。当您调用此方法时,ClientScriptManager
会处理所有这些问题。
答案 1 :(得分:3)
试试这个
__doPostBack('<%=btDemo.ClientID%>','OnClick');
注意开头的双下划线
如果用户点击按钮
,则应触发回发