是否可以在视图中使用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