需要从Javascript强制返回,而不是通过单击按钮发起的

Need to force post back from Javascript not initiated by a button click

本文关键字:单击 按钮 Javascript 返回      更新时间:2023-09-26

我需要在我的ASPX页面中使用JavaScript确认函数来确认基于c#代码中没有直接连接到按钮单击事件的条件的各种操作。例如,如果计算的记录数大于200,问"你想继续吗?",然后根据"是"或"否"单击执行相关操作。我的JavaScript定义为:

    <script type = "text/javascript">
    function Confirm(val) {
        var confirm_value = document.createElement("INPUT");
        confirm_value.type = "hidden";
        confirm_value.name = "confirm_value";
        if (confirm(val)) {
            confirm_value.value = "Yes";
        } else {
            confirm_value.value = "No";
        }
        document.forms[0].appendChild(confirm_value);
    }
</script>

并从后面的代码调用它,并使用RegisterStartupScript和Request获得响应。格式如下:

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "confirm_value", String.Format("Confirm('{0}');", msgstr), true);
            string confirmvalue = Request.Form["confirm_value"];

出现确认框,但是confirmvalue字符串总是"behind"。也就是说,如果我在确认框上点击"Yes",它会返回"No";但如果我停留在同一页面并再次执行该过程并单击"No",我将得到"Yes"返回;等等......问:如何强制回发confirmvalue,以便能够及时访问后面代码中的响应?

可能有四种方法可以实现这一点,有/没有post back:-

  1. 在代码隐藏文件中使用AjaxMethod属性:-

    [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public object DoSomething(int countValue) { //Do Something }

    然后从ascx文件中,您将能够通过执行类名点方法名来调用该方法。在本例中,方法名为DoSomething。

  2. 如果您在ascx文件中使用ScriptManager,那么您可以通过将脚本管理器的EnablePageMethods属性设置为true来启用页面方法调用。但是,您调用的方法应该是静态的。MSDN链接

    public static object DoSomething(int countValue) { //Do Something }

    在这里,你可以直接从JS中调用这个方法。

  3. 使用web服务如下:-

    [ScriptService] public class YourService { [WebMethod(EnableSession=true)] public object DoSomething(int countValue) { //Do Something } }

  4. 回传方式:-

    if (IsPostBack) { string ControlID = string.Empty; if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"])) { ControlID = Request.Form["__EVENTTARGET"]; Control postbackControl = Page.FindControl(ControlID); } }