在将值插入表格时显示加载栏

时间:2013-02-25 14:58:20

标签: c# asp.net-mvc-3 loops asynchronous

我将此代码基于此示例http://weblogs.asp.net/seanmcalinden/archive/2009/11/15/asynchronous-processing-in-asp-net-mvc-with-ajax-progress-bar.aspx 使用MVC3,C#,jQuery,Ajax ++

我的HTML

<div>
   <a href="#" id="startProcess">Start Long Running Process</a>
</div>
<br />
<div id="statusBorder">
    <div id="statusFill">
    </div>
</div>

html的javascript部分

    var uniqueId = '<%= Guid.NewGuid().ToString() %>';

    $(document).ready(function (event) {
        $('#startProcess').click(function () {
            $.post("SendToDB/StartLongRunningProcess", { id: uniqueId,
                                 //other parameters to be inserted like textbox

                                                             }, function () {
                $('#statusBorder').show();
                getStatus();
            });
            event.preventDefault;
        });
    });

    function getStatus() {
        var url = 'SendToDB/GetCurrentProgress/' + uniqueId;
        $.get(url, function (data) {
            if (data != "100") {
                $('#status').html(data);
                $('#statusFill').width(data);
                window.setTimeout("getStatus()", 100);
            }
            else {
                $('#status').html("Done");
                $('#statusBorder').hide();
                alert("The Long process has finished");
            };
        });
    }

全班帮助

public class ProgressBarManager
{

    private static object syncRoot = new object();

    /// <summary>
    /// Gets or sets the process status.
    /// </summary>
    /// <value>The process status.</value>
    private static IDictionary<string, int> ProcessStatus { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="MyLongRunningClass"/> class.
    /// </summary>
    public ProgressBarManager()
    {
        if (ProcessStatus == null)
        {
            ProcessStatus = new Dictionary<string, int>();
        }
    }

    /// <summary>
    /// Processes the long running action.
    /// This is how it was in sample code. Not used anymore.
    /// </summary>
    /// <param name="id">The id.</param>
    //public string ProcessLongRunningAction(string id)
    //{
    //    for (int i = 1; i <= 100; i++)
    //    {
    //        Thread.Sleep(100);
    //        lock (syncRoot)
    //        {
    //            ProcessStatus[id] = i;
    //        }
    //    }
    //    return id;
    //}

    public void SetStatus(string id, int value)
    {
        lock (syncRoot)
        {
            ProcessStatus[id] = value;
        }
    }

    /// <summary>
    /// Adds the specified id.
    /// </summary>
    /// <param name="id">The id.</param>
    public void Add(string id)
    {
        lock (syncRoot)
        {
            ProcessStatus.Add(id, 0);
        }
    }

    /// <summary>
    /// Removes the specified id.
    /// </summary>
    /// <param name="id">The id.</param>
    public void Remove(string id)
    {
        lock (syncRoot)
        {
            ProcessStatus.Remove(id);
        }
    }

    /// <summary>
    /// Gets the status.
    /// </summary>
    /// <param name="id">The id.</param>
    public int GetStatus(string id)
    {
        lock (syncRoot)
        {
            if (ProcessStatus.Keys.Count(x => x == id) == 1)
            {
                return ProcessStatus[id];
            }
            else
            {
                return 100;
            }
        }
    }
}

这是控制器,这是我可能做错的地方。

    delegate string ProcessTask(string id);
    ProgressBarManager longRunningClass = new ProgressBarManager();
    //Some global variables. I know it is not "good practice" but it works.
    private static int _GlobalSentProgress = 0;
    private static int _GlobalUsersSelected = 0;

    /// <summary>
    /// Starts the long running process.
    /// </summary>
    /// <param name="id">The id.</param>
    public void StartLongRunningProcess(string id,
                                        //other parameters
                                        )
    {
        longRunningClass.Add(id);

        int percentDone = 0;
        var batchId = Guid.NewGuid().ToString("N");
        var costd = cost.ToDecimal();
        int sent = 0;

        IEnumerable<BatchListModel> users;

        users = new UserService(_userRepository.Session).GetUsers(
                //several parameters)

        foreach (var c in users)
        {
            try
            {
                var usr = _userRepository.LoadByID(c.ID);

                var message = new DbLog
                {
                    //insert parameters
                };

                _DbLogRepository.Save(message);
                sent++;

                //MyLog.WriteLine("Sent = " + sent); This is  1 more each time it loops
                //MyLog.WriteLine("GlobalUsersSelected = " + _GlobalUsersSelected); This one is set in another function not shown.

                double _GlobalSentProgress = (double)sent / (double)_GlobalUsersSelected * 100;
                //MyLog.WriteLine("SentProgress = " + _GlobalSentProgress);

                if (percentDone < 100)
                {
                    //percentDone = doSomeWork();
                    percentDone = Convert.ToInt32(_GlobalSentProgress);
                    //MyLog.WriteLine("percentDone = " + percentDone); This one shows same as GlobalSentProgress except the decimals are removed
                    longRunningClass.SetStatus(id, percentDone);
                }

            }
            catch (Exception e)
            {
                MyLog.WriteLine("ERR:" + e);
            }
        }
        longRunningClass.Remove(id);


        //Under here is how it was done in the example tutorial. 
        //I think these should be implemented somehow.
        //This may be the root of my problem

        //ProcessTask processTask = new ProcessTask(longRunningClass.ProcessLongRunningAction);
        //processTask.BeginInvoke(id, new AsyncCallback(EndLongRunningProcess), processTask);


    }

    /// <summary>
    /// Ends the long running process.
    /// </summary>
    /// <param name="result">The result.</param>
    public void EndLongRunningProcess(IAsyncResult result)
    {
        ProcessTask processTask = (ProcessTask)result.AsyncState;
        string id = processTask.EndInvoke(result);
        longRunningClass.Remove(id);
    }

    /// <summary>
    /// Gets the current progress.
    /// </summary>
    /// <param name="id">The id.</param>
    public ContentResult GetCurrentProgress(string id)
    {
        this.ControllerContext.HttpContext.Response.AddHeader("cache-control", "no-cache");
        var currentProgress = longRunningClass.GetStatus(id).ToString();
        return Content(currentProgress);
    }

任何人都知道什么是错的?任何帮助非常感谢。我被困了几天。

在插入完成100%之前,不会输入一些应该更新“进度”的断点。现在,带有进度条的div永远不会出现。

编辑: 在执行插入的循环中,我确实有这个计算:

double _GlobalSentProgress = (double)sent / (double)_GlobalUsersSelected * 100;

然后我将_GlobalSentProgress转换为

中的普通int
percentDone = Convert.ToInt32(_GlobalSentProgress);

所以它不再有任何小数。

如果只有我可以发送这个“percentDone”变量(它完全显示我插入了多少百分比)异步进入javascript中的“data”变量,每次循环,它都可以。然后“数据”将始终执行“statusFill”并正确显示条形。

    function getStatus() {
        var url = 'SendToDB/GetCurrentProgress/' + uniqueId;
        $.get(url, function (data) {
            if (data != "100") {
                $('#status').html(data);
                $('#statusFill').width(data);
                window.setTimeout("getStatus()", 100);
            }
            else {
                $('#status').html("Done");
                $('#statusBorder').hide();
                alert("The Long process has finished");
            };
        });

但我说实话,这是我第一次处理异步变量,所以我很失落如何做这些事情。

2 个答案:

答案 0 :(得分:0)

如果我遇到这样的问题,我首先要做的是设置断点或调试器(在js中)并查看代码的哪些部分正在做某事。

你说你的状态栏永远不会显示,如果你看看它所说的Jquery.post documentation

  

请求成功时执行的回调函数。

这是因为你的查询没有成功,它永远不会显示。 所以首先要查看代码中的错误(C#)

答案 1 :(得分:0)

您希望设计师帮助显示进度条, 假设你用一些CSS div元素

<div id="divProgressBar" >/div>
 $(document).ready(function (event) {
    $('#startProcess').click(function () {
        $('#divProgressBar').show();//My code here
   }
}

function getStatus() {
    var url = 'SendToDB/GetCurrentProgress/' + uniqueId;
    $.get(url, function (data) {
        if (data != "100") {
            $('#status').html(data);
            $('#statusFill').width(data);
            window.setTimeout("getStatus()", 100);
        }
        else {
            $('#status').html("Done");
            $('#statusBorder').hide();
            $('#divProgressBar').hide();//My code here
            alert("The Long process has finished");
        };
    });
}

您还可以使用第三方JS来阻止用户界面。

http://www.malsup.com/jquery/block/