【问题标题】:ASP MVC4 upload file without form but with partial viewASP MVC4 上传文件没有表单但有部分视图
【发布时间】:2015-12-04 15:24:56
【问题描述】:

是否可以使用带有 Razor 的 ASP.NET MVC4 上传文件,而无需在视图中使用表单(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>

【问题讨论】:

  • Google Ajax 文件上传,您将获得解决方案。还要仔细检查支持的浏览器:)

标签: c# asp.net asp.net-mvc-4 razor


【解决方案1】:

好的,解决方法如下:

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

【讨论】:

  • 感谢@Santiago(而且响应速度也非常快!)。我很欣赏这些参考资料。我的大多数(编码)问题似乎都与 ajax/jQuery 相关,我认为我需要好好阅读一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 2018-04-09
相关资源
最近更新 更多