简体   繁体   中英

ASP MVC4 upload file without form but with partial view

Is it possible to upload a file using ASP.NET MVC4 with Razor without using forms (either BeginForm or <form> ) in the view.

My problem is I have a partial view on the main view to show infomation (a log), if I use forms I can get the information about the file being uploaded either via the HttpPostFileBase or Request.Files , however my partial view refresh, refreshes the entire page and I end up only seeing the partial view. If I don't use forms the partial view updates correctly, but I'm missing all information about the file.

I've tried preventDefault() in the ajax (which updates the partial view). But I can't seem to get it to work.

Here is my code:

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

View:

<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>

Ok, so here is the solution:

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

Here are some references:

MDN | Using FormData

jQuery | $.ajax()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM