在表中插入值时显示加载栏

本文关键字:显示 加载 插入 | 更新日期: 2023-09-27 18:00:54

我将此代码基于此示例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"变量中,它就会起作用。然后"数据"会一直做它的"状态填充",并正确显示条形图。

    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");
            };
        });

但我必须说实话,这是我第一次处理异步变量,所以我非常不知道如何做这些事情。

在表中插入值时显示加载栏

如果我遇到这样的问题,我要做的第一件事就是设置断点或调试器(在js中(,看看代码的哪些部分在做什么。

你说你的状态栏从来没有显示过,如果你看Jquery.post文档,它会显示

如果请求成功,则执行的回调函数。

这是因为您的查询没有成功,它将永远不会显示。因此,它首先要查看代码(C#(

中的错误位置

您想要获得设计器帮助来显示进度条,假设您的div元素带有一些CSS

<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来阻止UI。

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