C# 代码隐藏如何触发 JavaScript 代码?

发布于 2024-11-09 15:22:14 字数 4267 浏览 1 评论 0原文

我有一些 JavaScript 代码,它将显示一个模式对话框,要求用户在运行可能需要几秒钟才能运行的 Web 服务时等待。无法弄清楚如何从服务器中运行的 C# 代码启动 JS 代码。以下是场景:

1) 用户单击启动服务器代码的 asp:Button 代码。 2) 服务器代码[以某种方式]触发浏览器事件,该事件启动调用 Web 服务的 JS 代码

JS 代码如下所示:

<form id="form1" runat="server">
<div>
    <script type="text/javascript">
        $(function () {
            $('#btn_BeginProcessB').click(function (event) {
                event.preventDefault();
                var $Seconds = $("INPUT[id*='txtSeconds']").val();
                var $Message = $("INPUT[id*='txtMessage']").val();
                var $WorkingMessage = $('#WorkingMessage');
                $WorkingMessage.text($Message);

                var $this = $(this);
                var $Loader = $('#Loader');
                // show loading indicator              
                $Loader.show();
                $("body").css({ background: "#C8C5C5" });
                // Begin process
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ Seconds: $Seconds }),
                    url: 'SimpleWebService.asmx/LongRunningProcess',
                    error: function (xhr, textStatus, errorThrown) {
                        alert('Error! ' + errorThrown);
                        // show button
                        // hide loading indicator                
                        $Loader.hide();
                    },
                    success: function (data) {
                        alert("Data:" + data.d);
                        // show button
                        // hide loading indicator                
                        $Loader.hide();
                        $("body").css({ background: "#FFFFFF" });
                    }
                });

            });
        });
    </script>
    <script type="text/javascript">
        function LoadPageWorking() {
            var $Seconds = $("INPUT[id*='txtSeconds']").val();
            var $Message = $("INPUT[id*='txtMessage']").val();
            var $WorkingMessage = $('#WorkingMessage');
            $WorkingMessage.text($Message);
            var $data = JSON.stringify({ Seconds: $Seconds });
            PageWorking('Loader', 'SimpleWebService.asmx/LongRunningProcess', $data, PageWorkingSuccess, PageWorkingError);  
        };

        function PageWorkingSuccess(data) {
            $("SPAN[id*='lblResult']").html("<br /><b>Result:</b>" + data.d + "<br />");
            $('body').css('background', originalBackground);
        };

        function PageWorkingError(xhr, textStatus, errorThrown) {
            alert('Error! ' + errorThrown);
            $('body').css('background', originalBackground);
        }
    </script>
    <!--- HTML --->
    <div id="Page">
        <h1>
            Long Running Process Test Page</h1>
        <p>
            This site demonstrates how to invoke a long running process and let the user know
            that the process is underway. When the button is clicked, it calls a web service
            that sleeps for the designated number of seconds and returns a message.</p>
        <br />
        Enter number of seconds for worker process to sleep:
        <asp:TextBox ID="txtSeconds" runat="server" Width="25" Text="3" /><br />
        Enter the message to be displayed while the process is working:
        <asp:TextBox ID="txtMessage" runat="server" Text="Working...(please be patient)"
            Width="300px" /><br />
        <asp:Label ID="lblResult" runat="server" />
        <br />
        <input type="button" id="btnBegin" value="Click to test LoadPageWorking function"
            onclick="LoadPageWorking();" />
    </div>
    <div id="Loader">
        <center>
        <span id="WorkingMessage">Default Loader Message</span>
            <div class="ProgressBar-Animated">
                &nbsp;</div>
        </center>
    </div>
</div>
</form>

我可以在 C# 事件中编写哪些代码来触发 LoadPageWorking() JS 函数?

I have some JavaScript code that will display a modal dialogue box asking the user to wait while it runs a web service that could take several seconds to run. What cannot figure out is how to launch the JS code from my C# code running in the server. Here is the scenario:

1) User clicks asp:Button code that launches server code.
2) Server code [somehow] fires a browser event that launches the JS code that calls the web service

The JS code looks like this:

<form id="form1" runat="server">
<div>
    <script type="text/javascript">
        $(function () {
            $('#btn_BeginProcessB').click(function (event) {
                event.preventDefault();
                var $Seconds = $("INPUT[id*='txtSeconds']").val();
                var $Message = $("INPUT[id*='txtMessage']").val();
                var $WorkingMessage = $('#WorkingMessage');
                $WorkingMessage.text($Message);

                var $this = $(this);
                var $Loader = $('#Loader');
                // show loading indicator              
                $Loader.show();
                $("body").css({ background: "#C8C5C5" });
                // Begin process
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ Seconds: $Seconds }),
                    url: 'SimpleWebService.asmx/LongRunningProcess',
                    error: function (xhr, textStatus, errorThrown) {
                        alert('Error! ' + errorThrown);
                        // show button
                        // hide loading indicator                
                        $Loader.hide();
                    },
                    success: function (data) {
                        alert("Data:" + data.d);
                        // show button
                        // hide loading indicator                
                        $Loader.hide();
                        $("body").css({ background: "#FFFFFF" });
                    }
                });

            });
        });
    </script>
    <script type="text/javascript">
        function LoadPageWorking() {
            var $Seconds = $("INPUT[id*='txtSeconds']").val();
            var $Message = $("INPUT[id*='txtMessage']").val();
            var $WorkingMessage = $('#WorkingMessage');
            $WorkingMessage.text($Message);
            var $data = JSON.stringify({ Seconds: $Seconds });
            PageWorking('Loader', 'SimpleWebService.asmx/LongRunningProcess', $data, PageWorkingSuccess, PageWorkingError);  
        };

        function PageWorkingSuccess(data) {
            $("SPAN[id*='lblResult']").html("<br /><b>Result:</b>" + data.d + "<br />");
            $('body').css('background', originalBackground);
        };

        function PageWorkingError(xhr, textStatus, errorThrown) {
            alert('Error! ' + errorThrown);
            $('body').css('background', originalBackground);
        }
    </script>
    <!--- HTML --->
    <div id="Page">
        <h1>
            Long Running Process Test Page</h1>
        <p>
            This site demonstrates how to invoke a long running process and let the user know
            that the process is underway. When the button is clicked, it calls a web service
            that sleeps for the designated number of seconds and returns a message.</p>
        <br />
        Enter number of seconds for worker process to sleep:
        <asp:TextBox ID="txtSeconds" runat="server" Width="25" Text="3" /><br />
        Enter the message to be displayed while the process is working:
        <asp:TextBox ID="txtMessage" runat="server" Text="Working...(please be patient)"
            Width="300px" /><br />
        <asp:Label ID="lblResult" runat="server" />
        <br />
        <input type="button" id="btnBegin" value="Click to test LoadPageWorking function"
            onclick="LoadPageWorking();" />
    </div>
    <div id="Loader">
        <center>
        <span id="WorkingMessage">Default Loader Message</span>
            <div class="ProgressBar-Animated">
                 </div>
        </center>
    </div>
</div>
</form>

What code can I write in my C# event that will fire the LoadPageWorking() JS function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

花之痕靓丽 2024-11-16 15:22:14

即使您有服务器端按钮控件,您也可以使用它的 onclientclick 属性直接调用 javascript。但是,如果您必须从后面的代码调用脚本,则可以使用 ClientScriptManager.RegisterStartupScript()ClientScriptManager.RegisterClientScriptBlock() 根据您的要求。那里有很多例子。

Even if you have a server side button control, you can use it's onclientclick property to call javascript directly. But if you have to call the script from code behind, you can use ClientScriptManager.RegisterStartupScript() or ClientScriptManager.RegisterClientScriptBlock() based on your requirement. There are plenty of examples out there.

走过海棠暮 2024-11-16 15:22:14

让按钮触发页面工作功能,创建一些您正在工作的指示器,触发 ajax 请求,当它返回时完成工作并隐藏指示器。无需转到代码后面。

Have the button trigger a page working function that creates some indicator that you are working, fire off the ajax request, and when it comes back finish the working and hide the indicator. No need to ever have to go to code behind.

剧终人散尽 2024-11-16 15:22:14

为什么不让 LoadPageWorking() 启动服务器,然后显示 JS 模式弹出窗口?您可以让弹出窗口轮询您的服务以确定它是否已完成,并在完成时隐藏自己。

Why don't you have your LoadPageWorking() start the server, then show the JS modal popup? You can have your popup poll your service to determine if it's completed, and hide itself when it is.

四叶草在未来唯美盛开 2024-11-16 15:22:14

您应该尝试使用 RegisterClientScriptBlock 方法。它将允许您动态地将脚本部分添加到页面的源代码中。您可以包含任何您想要的 Javascript,包括调用页面中已定义的方法。

You should try using the RegisterClientScriptBlock method. It will allow you to dynamically add script sections to your page's source. You can include any Javascript you'd like, including invocation of a method already defined in the page.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文