简体   繁体   English

通过单击表单上的ac#asp.net按钮,如何在继续执行下一行代码之前执行一行代码?

[英]By the click of a c# asp.net button on a form, how can I execute a line of code before moving on to the next lines of code?

Using c# code, I have a button on a webpage which will run a PowerShell process (see code below). 使用c#代码,我在网页上有一个按钮,它将运行PowerShell进程(请参见下面的代码)。 This process takes a little while to run, so when I click the button I would like to display a message in a label stating that the process is running. 该过程需要一点时间才能运行,因此,当我单击按钮时,我想在标签中显示一条消息,指出该过程正在运行。 then once the process has finished, change the label message to state that the process ahs finished. 然后,一旦过程完成,则更改标签消息以表明过程已完成。 My current code is: 我当前的代码是:

protected void button_Click(object sender, EventArgs e)
        {
            label.Text = "Running Process...";

            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = @"powershell.exe";
            startInfo.Arguments = @"C:\PowerShell\script.ps1";
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();

            label.Text = "Finished Process. ";

      }

This currently does not display the initial message of "Running Process...". 当前,此消息不显示“正在运行过程...”的初始消息。 It just runs through the whole code and displays the "Finished Process" message. 它只运行整个代码,并显示“ Finished Process”消息。

So I need a way of committing the first line of code to fill the label and then move on to the rest of the code but am stuck as to how to do this??? 因此,我需要一种提交第一行代码以填充标签,然后继续进行其余代码的方法,但对于如何执行此操作却一无所获?

Any help please is appreciated. 任何帮助,请表示赞赏。

Johnathan. 乔纳森。

You could use AJAX to get this done. 您可以使用AJAX完成此操作。

You could post it using jquery/ajax, set the message you want on begin of the process and and finish message when the process finishes. 您可以使用jquery / ajax发布它,在过程开始时设置所需的消息,并在过程结束时完成消息。

Aspx code Aspx代码

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

<script type="text/javascript">

    function BeginProcess() {
        // Create an iframe.
        var iframe = document.createElement("iframe");

        // Point the iframe to the location of
        //  the long running process.
        iframe.src = "Process.aspx";

        // Make the iframe invisible.
        iframe.style.display = "none";

        // Add the iframe to the DOM.  The process
        //  will begin execution at this point.
        document.body.appendChild(iframe);

        // Disable the button and blur it.
         document.getElementById('trigger').blur();
    }

    function UpdateProgress(PercentComplete, Message) {
        document.getElementById('ContentPlaceHolder2_lbDownload').setAttribute("disabled", "true");
        document.getElementById('trigger').value = PercentComplete + '%: ' + Message;

    }


  </script>
 </asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
 <ContentTemplate>

  <input type="submit" value="Start BackUp Process!" 
id="trigger" onclick="BeginProcess(); return false;"
style="width: 250px;" />

</ContentTemplate>
 </asp:UpdatePanel>


  <asp:UpdateProgress ID="UpdateProgress1" 
 AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>  
     </ProgressTemplate> 
</asp:UpdateProgress>


 </asp:Content>

Code behind .cs code .cs代码后面的代码

 public partial class Process : System.Web.UI.Page
 {
  protected void Page_Load(object sender, EventArgs e)
{

    StringBuilder SB = new StringBuilder();
    // Padding to circumvent IE's buffer.
    Response.Write(new string('*', 256));
    Response.Flush();

    // Initialization
    UpdateProgress(0, "Initializing task.");


    try
    {


        foreach (yourloophere)
        {

                    UpdateProgress(increment, db.Name + " Backup Started....");
            //your process code
                    UpdateProgress(increment, db.Name + " Backup Completed!");

//your process code SB.Append(db.Name + "BackUp Complted!"); //您的过程代码SB.Append(db.Name +“ Backup Complted!”);

    //your process code
            SB.Append("<br/>");



        }


        // All finished!
        UpdateProgress(100, "All Database BackUp Completed!");

    }
    catch (Exception ex)
    {
        UpdateProgress(0, "Exception: " + ex.Message);

        SB.Append("Back Up Failed!");
        SB.Append("<br/>");
        SB.Append("Failed DataBase: " + DBName);
        SB.Append("<br/>");
        SB.Append("Exception: " + ex.Message);

    }


}


protected void UpdateProgress(double PercentComplete, string Message)
{
    // Write out the parent script callback.
    Response.Write(String.Format("<script type=\"text/javascript\">parent.UpdateProgress({0}, '{1}');</script>", PercentComplete, Message));
    // To be sure the response isn't buffered on the server.    
    Response.Flush();
}


 }

Have a look at the asp lifecycle. 看看ASP的生命周期。 You cant change the page via serverside code without doing a postback. 您不能通过服务器端代码更改页面而无需回发。 Thats what you are doing when clicking an asp button, etc.. 那就是您单击asp按钮等时正在做的事情。

If you want to show a loading indicator youll have to create it before running the long running code. 如果要显示加载指示器,则必须在运行长时间运行的代码之前创建它。 Otherwise the indicator will never be shown to the user because he does not receive a new page. 否则,该指示符将永远不会显示给用户,因为他没有收到新页面。

Here you have 2 options - do a postback place the loading indicator and do another postback (I would not recommend that) or just show something via JS. 在这里,您有2个选项-进行回发,放置加载指示器,然后进行另一回发(我不建议这样做),或者仅通过JS显示内容。

I created a Weave to show you the basic functionality. 我创建了一个Weave来向您展示基本功能。 -- stolen from http://oracleinsights.blogspot.de/2009/12/how-to-create-loading-indicator_13.html -从http://oracleinsights.blogspot.de/2009/12/how-to-create-loading-indicator_13.html被盗

This will show a loading indicator serverside code is running. 这将显示一个加载指示器服务器端代码正在运行。

You can try adding inline javascript code to change the label. 您可以尝试添加内联JavaScript代码来更改标签。

<asp:Button ID="button" runat="server" OnClick="button_Click" Text="Click" 
    OnClientClick="this.value = 'Running Process...'" />

This will appear the moment you click the button and then the label will change to Finished Process. 当您单击按钮时,这将出现,然后标签将更改为“ Finished Process. when the page is reloaded. 页面重新加载时。

You can do this on ajax, 您可以在ajax上执行此操作

function ShowProcessing()
{
    $('#label').text('Running Process...');
    // call pagemethod with your functionality
    // Let's success callback is OnSuccess
}

function OnSuccess()
{
     $('#label').text('Finished Process.');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM