1
使用MVC3,C#,jQuery的,阿賈克斯++異步進度條
我的HTML
<div>
<a href="#" id="startProcess">Start Long Running Process</a>
</div>
<br />
<div id="statusBorder">
<div id="statusFill">
</div>
</div>
的HTML
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';
$.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");
};
});
}
這的JavaScript部分中的部分是控制器。
//Some global variables. I know it is not "good practice" but it works.
private static int _GlobalSentProgress = 0;
private static int _GlobalUsersSelected = 0;
public void StartLongRunningProcess(string id,
//other parameters
)
{
int percentDone = 0;
int sent = 0;
IEnumerable<BatchListModel> users;
users = new UserService(_userRepository.Session).GetUsers(
//several parameters)
foreach (var c in users)
{
var usr = _userRepository.LoadByID(c.ID);
var message = new DbLog
{
//insert parameters
};
_DbLogRepository.Save(message);
sent++;
double _GlobalSentProgress = (double)sent/(double)_GlobalUsersSelected * 100;
if (percentDone < 100)
{
percentDone = Convert.ToInt32(_GlobalSentProgress);
}
//this is supposed to give the current progress to the "GetStatus" in the javascript
public int GetCurrentProgress()
{
return _GlobalSentProgress;
}
現在,帶進度條的div永遠不會顯示出來。這是誠實的一種破碎。但我希望你能理解我的邏輯。
在循環做插入,我確實有這樣計算:
double _GlobalSentProgress = (double)sent/(double)_GlobalUsersSelected * 100;
然後我的_GlobalSentProgress轉換爲常規INT在
percentDone = Convert.ToInt32(_GlobalSentProgress);
,使其不再具有任何小數任何更長的時間。
如果我只能每次循環發送這個「percentDone」或「_GlobalSentProgress」變量(它完全顯示我插入的百分比)異步到JavaScript中的「數據」變量,它會工作。然後,「數據」將始終執行「狀態填充」並正確顯示欄。這是我使用的邏輯。
我相信爲了拋向四周來完成,這是「異步」字。我已經看了2個非常有前途的指南,但我無法使它與我的循環一起工作。
任何人有我如何能做到這一點建議嗎?