是否可以在視圖中使用ASP.NET MVC4和Razor上傳文件,而不使用表單(BeginForm
或<form>
)。ASP MVC4上傳文件不帶表格但部分視圖
我的問題是我對主視圖的局部視圖來顯示信息來源(日誌),如果我用的形式,我可以得到有關文件的信息被上傳或者通過HttpPostFileBase
或Request.Files
,但我的部分觀點刷新,刷新整個頁面,我最終只看到局部視圖。如果我不使用表單,局部視圖會正確更新,但我錯過了關於該文件的所有信息。
我試過在ajax中的preventDefault()
(它更新了局部視圖)。但我似乎無法讓它工作。
這裏是我的代碼:
控制器:
[HttpPost]
public PartialViewResult FileUpload(MyViewModel vm)
{
vm.Log = new ScriptLog();
if (Request.Files.Count < 1)
{
vm.Log.Add("File information missing");
}
else if (Request.Files[0].ContentLength < 1)
{
vm.Log.Add("File empty");
}
else
{
// Upload file and fill log
vm.Log.Add("File uploaded successfully.");
}
return PartialView("Log", vm.Log);
}
查看:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
@model ViewModels.MyViewModel
<input type="file" name="file" accept="application/vnd.ms-excel" />
<input id="uploadButton" type="submit" value="Upload" />
@*
Without the form (BeginForm or <form>) the partial view correctly updates in place.
But it is missing any file information.
With it I can get the file information but I can't update the partial view in place.
*@
<div id="log">
@{ if (Model != null)
{
Html.RenderPartial("Log", Model.Log);
}
}
</div>
<script>
$("input[id=uploadButton]").on("click", function (e) {
//e.preventDefault(); // preventing the default action
//alert("Here")
$.post("/MyContoller/FileUpload")
.done(function (partialResult) {
$("#log").html(partialResult);
})
});
</script>
谷歌的Ajax文件上傳,你會得到解決。仔細檢查支持的瀏覽器也:) – Shyju