2015-12-04 33 views
3

是否可以在视图中使用ASP.NET MVC4和Razor上传文件,而不使用表单(BeginForm<form>)。ASP MVC4上传文件不带表格但部分视图

我的问题是我对主视图的局部视图来显示信息来源(日志),如果我用的形式,我可以得到有关文件的信息被上传或者通过HttpPostFileBaseRequest.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> 
+0

谷歌的Ajax文件上传,你会得到解决。仔细检查支持的浏览器也:) – Shyju

回答

2

好了,所以这里是解决方案:

$("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); 
     } 
    }); 
}); 

这里有一些参考:

MDN | Using FormData

jQuery | $.ajax()

+0

谢谢@圣地亚哥(和真的快速响应呢!)。我很欣赏这些参考。我的大部分(编码)问题似乎都与ajax/jQuery相关,我认为我需要对其进行一些阅读。 –

+0

您的欢迎;) –