我在MVC上传相对较新,所以我有一点澄清。我正在执行ajax上传操作。
上传操作完全正常,但上传后,重定向到新页面,我不知道如何阻止它上传。 我也使用了EmptyResult,但仍然发生了同样的事情。我错过了什么?
@using(Html.BeginForm())
{
<input type="file" id="fileInput" />
<button onclick="startUpload();">Upload</button>
<br />
<progress id="progressBar" max="100" value="0" />
}
<script>
function startUpload() {
var fileInput = document.getElementById("fileInput");
if (fileInput.files.length == 0) {
alert("Please choose a file");
return;
}
var progressBar = document.getElementById("progressBar");
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
// alert("in progress");
var percentComplete = (e.loaded / e.total) * 100;
progressBar.value = percentComplete;
};
xhr.onload = function () {
};
xhr.onerror = function () {
alert("Error! Upload failed. Can not connect to server.");
};
xhr.onreadystatechange = function () {
};
progressBar.value = 0;
xhr.open("POST", "/Home/Index", true);
xhr.setRequestHeader("Content-Type", 'application / json');
xhr.send(fileInput.files[0]);
}
</script>
[HttpPost]
public EmptyResult Index(FormCollection frm)
{
// Create JSON Response
var jsonData = new
{
status = "success",
message = "message"
};
return null;
}
答案 0 :(得分:0)
您可以在按钮的onclick函数调用中传递事件值,以便稍后操作事件处理:
<button onclick="startUpload(event);">Upload</button>
然后在你的javascript中,你可以要求它忽略默认的事件处理(在这种情况下提交表单):
function startUpload(event) {
//do all those stuff
//event.preventDefault() should handle most of the browsers
//but for better compatibility, it's 3 lines here
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
return false;
}