这是我的问题:
可以更新页面服务器端whitout重新加载吗?
让我解释一下:
我有一个页面,其中有一个表单,用户上传一个包含许多行的.csv以添加到数据库中。
但插入需要一些时间,我想实现一个引导进度条,但我无法想象如何从控制器更新进度条值。
答案 0 :(得分:0)
有可能。您可以使用SignalR(或其他库)向客户端发送推送通知。
答案 1 :(得分:0)
我终于只使用了一些Ajax和progress对象。
这是有人需要的代码:
ProgressHandler.cs
public class ProgressHandler
{
public int Progress { get; set; }
public int MaxProgress { get; set; }
public int Percentage { get; set; }
public String PercentageStr { get; set; }
public String[] Events { get; set; }
public String Statut { get; set; }
public static ProgressHandler PH { get; set; }
public ProgressHandler()
{ }
public ProgressHandler(int maxProgress)
{
MaxProgress = maxProgress;
PH = this;
}
public static ProgressHandler Current()
{
return PH;
}
public void Init()
{
Progress = 0;
MaxProgress = 0;
Statut = "Waiting";
}
public int GetPercentage()
{
if (MaxProgress != 0)
{
return (int)(((float)Progress / (float)MaxProgress) * 100);
}
else
{
return 0;
}
}
public int EventSize()
{
if(Events!=null)
{
return Events.Count();
}
return 0;
}
}
插入功能:
public FileContentResult AddEmployeeListSubmit(AddEmployeeList model)
{
//working with file
_progressHandler.MaxProgress = emps.Count;
_progressHandler.Statut = "Running";
//working with file and insert...
int iter = 0;
foreach(var Employee in EmployeeList)
{
//make insert in db
iter++;
_progressHandler.Progress = iter;
}
_progressHandler.Statut = "Complete";
_progressHandler.Events = Errors.ToArray();
return something;
}
InsertPage.cshtml
<div id="updateBar" hidden>
<h1>Update in progress : <span class="label label-info" id="progressDisp"></span></h1>
<div class="progress">
<div class="progress-bar progress-bar-striped active" id="insertProgress" role="progressbar"
aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>
</div>
和JS可以取得进展:
$(document).ready(function () {
var myInterval = setInterval(function () {
getProgress();
}, 500);
});
function getProgress() {
$.ajax({
type: "POST",
data: "",
url: "/Login/GetProgress",
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
if (response.statut == "Running")
$("#updateBar").slideDown();
if (response.statut == "Complete") {
$("#progressDisp").text("Complete").removeClass("label-info").addClass("label-success");
$("#insertProgress").css("width", "100%").attr('aria-valuenow', 100).text("100%");
if (response.events.length > 0 && !$("#insertError").is(":visible")) {
$.each(response.events, function (key, value) {
console.log(key + ":" + value);
$("#insertError").html($("#insertError").html()+"<br><strong> Insert Error </strong>" + value);
});
$("#insertError").slideDown();
}
}
else {
$("#insertProgress").css("width", response.percentage + "%").attr('aria-valuenow', response.percentage).text(response.percentageStr + "%");
$("#progressDisp").text(response.progress + "/" + response.maxProgress);
}
},
error: function (response) {
console.log("error")
}
});
}