[英]ASP MVC4 upload file without form but with partial view
是否可以使用帶有Razor的ASP.NET MVC4上傳文件,而無需在視圖中使用表單( BeginForm
或<form>
)。
我的問題是我在主視圖上有部分視圖來顯示信息(日志),如果我使用表單我可以通過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>
好的,這是解決方案:
$("input[id=uploadButton]").on("click", function (e) {
var fd = new FormData();
var input = document.querySelector("input");
//fd.append({name of you variable in ViewModel}, value)
fd.append('file', input.files[0]);
$.ajax({
url: '/MyContoller/FileUpload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
以下是一些參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.