3

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>
1
  • Google Ajax file upload and you will get solutions. Double check the supported browsers also :) Commented Dec 4, 2015 at 15:34

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Santiago (and really fast response too!). I appreciate the references. Most of my (coding) problems seem to be ajax/jQuery related, think I need to do a good bit of reading up on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.