ASP MVC4使用局部视图上传文件而无需表单

3

在ASP.NET MVC4中使用Razor上传文件是否可以不使用表单(无论是BeginForm还是<form>)在视图中进行。

我的问题是,我在主视图上有一个部分视图用于显示信息(日志),如果我使用表单,我可以通过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>

谷歌Ajax文件上传,你会得到解决方案。也要仔细检查支持的浏览器 :) - Shyju
1个回答

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 | 使用 FormData

jQuery | $.ajax()


感谢@Santiago(回复非常迅速!)我很感激您提供的参考资料。我的大部分(编码)问题似乎与ajax / jQuery有关,我想我需要好好研究一下它。 - B_D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接