c# - ASP MVC4上传文件没有表单但有部分 View

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

是否可以使用带有 Razor 的 ASP.NET MVC4 上传文件,而无需在 View 中使用表单(BeginForm<form>)。

我的问题是我在主视图上有一个部分 View 来显示信息(日志),如果我使用表单,我可以通过 HttpPostFileBase 获取有关正在上传的文件的信息。或 Request.Files ,但是我的局部 View 刷新,刷新了整个页面,我最终只看到了局部 View 。如果我不使用表单,部分 View 会正确更新,但我会丢失有关该文件的所有信息。

我试过了 preventDefault()在 ajax 中(更新局部 View )。但我似乎无法让它工作。

这是我的代码:

Controller :

[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);
      }
    });
});

这里有一些引用:

MDN | Using FormData

jQuery | $.ajax()

关于c# - ASP MVC4上传文件没有表单但有部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091695/

相关文章:

asp.net-mvc - 使用 TypeScript 0.9.1.1 将 TypeScript 文件添加到 MVC4 应用程序

c# - 是否可以像在 VS C++ 中一样从 C# DLL 导出函数?

c# - 小数点使用逗号,千位 rdlc 报告使用句点

c# - 以对象列表作为属性的 MVC 模型

c# - 在 asp.net 中为 TextBox 添加格式

c# - 生成唯一的随机数

asp.net-mvc-4 - 如何使用 .dll 文件在 IIS 上部署网站

c# - LINQ 中的 If Else

c# - System.IO.Path.GetDirectoryName 使路径无效

c# - ElasticSearch简单示例不起作用C#