[英]Calling a ScriptMethod on form submission?
当我使用OnClientClick属性从ASP.NET按钮调用ScriptMethod时,ScriptMethod返回95%的时间(显示警告框),然后页面提交。
如果我从HTML输入按钮调用该方法,则ScriptMethod会返回100%的时间,但是当然页面不会提交。 如果我将类型更改为提交,那么我将返回到随后的95%。
我是否需要更改方法,并在ScriptMethod返回后从javascript调用commit,还是有一种方法可以使这种方法100%的成功? 通过成功,我的意思是实际上在表单提交之前100%的时间都在返回。 ScriptMethod永远不会真正失败。
页:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ScriptServiceMadness._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="Chewbacca.asmx" />
</Services>
</asp:ScriptManager>
<div>
<asp:TextBox ID="VerifyPostbackTextBox" runat="server" Text="true" />
<asp:Button ID="SubmitFormButton" runat="server" OnClientClick="attack()" Text="Works 90%" OnClick="SubmitFormButton_Click" />
<input type="button" id="InputButton" value="Works 100%" onclick="attack()" />
</div>
</form>
<script type="text/javascript">
function attack()
{
ScriptServiceMadness.Chewbacca.ShootImperialProbeDroid(true, speak, youvefailedme);
}
function speak(result)
{
alert(result);
}
function youvefailedme(error)
{
alert(error);
}
</script>
</body>
</html>
后面的代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace ScriptServiceMadness
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitFormButton_Click(object sender, EventArgs e)
{
VerifyPostbackTextBox.Text = DateTime.Now.Ticks.ToString();
}
}
}
ScriptService:
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Web.Script.Services;
using System.Threading;
namespace ScriptServiceMadness
{
/// <summary>
/// Summary description for Chewbacca
/// </summary>
[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class Chewbacca : System.Web.Services.WebService
{
[ScriptMethod]
[WebMethod]
public string ShootImperialProbeDroid(bool letHanDoIt)
{
if (letHanDoIt)
{
return "rrrroooorrrr";
}
else
{
return "rrrraaaarrrr";
}
}
}
}
有趣的一件事...在编写此问题时,我从SciptMethod中删除了bool参数,它似乎可以100%地起作用。 当然这可能是巧合。
由于脚本方法是异步执行的,因此您不能保证它会在表单回发之前返回。 在线部署并且用户与Web服务的连接速度较慢时,更改不会增加。 我可能建议您在收到响应后通过调用__doPostBack例程手动进行回发。
你忘了 :
using TheForce;
namespace Luke {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.