上载MVC文件时在浏览器中刷新C# [英] Refresh in browser when uploading mvc file c #
问题描述
我通过调用MVC C#驱动程序上传了AJAX文件,但是浏览器刷新并重新加载了页面.
I have an AJAX file upload by call to MVC C# driver, but the browser refreshes and reloads the page.
但是,如果我评论将文件保存在驱动程序中的那行是不会发生的,只有当文件保存在服务器上时. File.SaveAs (fname);
But if I comment the line that saves the file in the driver does not happen that is only when the file is saved on the server. File.SaveAs (fname);
MVC控制器:
[HttpPost]
public ActionResult UploadDocument()
{
if (Request.Files.Count > 0)
{
try
{
FileUpdateDto fileModal = new FileUpdateDto();
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
string fname;
DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/Content/Document/" + UserId).ToString());
if (!directory.Exists)
{
Directory.CreateDirectory(Server.MapPath("~/Content/Document/" + UserId).ToString());
}
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
var guidnew = Guid.NewGuid();
fname = Path.Combine(Server.MapPath("~/Content/Document/" + UserId), guidnew + "." + fname.Split('.')[1].ToString());
fileModal.FileName = fname;
fileModal.Path = directory.ToString();
fileModal.DateFileUpload = DateTime.Now;
file.SaveAs(fname); // If I comment this line without refreshing the browser but does not save the file
}
return Json(fileModal);
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
使用JavaScript调用Ajax:
Call Ajax in JavaScript:
UploadDocument: function () {
if (window.FormData !== undefined) {
var fileUpload = $("#AdviserFileUpload").get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
//fileData.append('username', 'Manas');
$.ajax({
url: site.baseUrl + '/Api/Upload/Document',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
__this._AdviserDocumentFile = result;
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
}
推荐答案
我相信我找到了解决方案.原因是Visual Studio的保存时启用重新加载"属性为True.
I believe I found the solution. The cause is that Visual Studio's "Enable Reload on Save" property is True.
转到工具-选项-网络-浏览器保存时重新加载-启用保存时重新加载,并将其设置为false.
Go to Tools - Options - Web - Browser Reload on Save - Enable Reload on Save and make it false.
我正在使用VS2015,这对我有用,希望它对您也有用.
Im working with VS2015 and this worked for me, hope it works for you too.
这篇关于上载MVC文件时在浏览器中刷新C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!