Solved

Jquery AJAX File Upload with form data

Posted on 2014-12-20
4
567 Views
Last Modified: 2014-12-23
I am using Razor, c# and Jquery to attempt to upload a file - along with the form data.

Currently I have this:
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { enctype = "multipart/form-data", id = "uploadForm" }))
<input id="fileupload" type="file" name="attachmentFile" required />
<input type="hidden" name="Id" value="@Model.Id" />
<ul>
                @foreach (var location in Model.testLocation)
                {
                    <li><label><input type="radio" name="testLocation" required value="@location.Value" @(location.Selected ? "checked='checked'" : "") />@location.Text</label></li>
                }
            </ul>
<button type="submit" class="btn">Upload</button>

Open in new window


No I am trying to use this AJAX to upload the file asynchronously.

$("form#uploadForm").submit(function () {
        var testLocation = $("input:radio[name='testLocation']:checked").val();
        $.ajax({
            url: "@Html.Raw(Url.Action("MyAction", "MyController", new { Id = Model.Id, testLocation = "abc" }))".replace("abc", testLocation),
            type: 'POST',
            async: false,
            success: function (data) {
                $('#errors').text(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });

        return false;
    });

Open in new window



And my controller looks like this:

[HttpPost]
	    public ActionResult MyAction(int Id, HttpPostedFileBase attachmentFile, TestLocation testLocation)
	    {
            //do some stuff and return errors.
	    }

Open in new window


However, my attachmentFile is always null?
0
Comment
Question by:Al4ddin2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 25

Assisted Solution

by:apeter
apeter earned 250 total points
ID: 40511872
Since attachmentFile is not in url so it doesn't map to it.

To get your attachment use Request object. Inside your action use below code.

HttpPostedFileBase myFile = Request.Files["fileupload"];
0
 

Author Comment

by:Al4ddin2
ID: 40512552
It's still coming through as null?
0
 
LVL 22

Accepted Solution

by:
ambience earned 250 total points
ID: 40513356
You are not submitting the form with $.ajax therefore the file is not even uploaded to the server. There is no other HTML only way to upload a file from the client side except through submitting the form. In HTML5, however, the new XMLHTppRequest2 object has some new API that allows async/ajax upload of files (http://www.sitepoint.com/html5-ajax-file-upload/)

That said, since you are using jQuery you should be able to find a plugin for ajax upload that gracefully regresses and uses the best available method for uploading a file async.
0
 

Author Comment

by:Al4ddin2
ID: 40514462
Hi. Thanks I have found the Ajax form plugin which seems to do exactly that.
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to implement server side field validation and display customized error messages to the client.
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question