Solved

Jquery AJAX File Upload with form data

Posted on 2014-12-20
4
516 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
  • 2
4 Comments
 
LVL 25

Assisted Solution

by:apeter
apeter earned 250 total points
Comment Utility
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
Comment Utility
It's still coming through as null?
0
 
LVL 22

Accepted Solution

by:
ambience earned 250 total points
Comment Utility
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
Comment Utility
Hi. Thanks I have found the Ajax form plugin which seems to do exactly that.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Convert jquery ajax call to pure javascript 3 56
Pass through dll 2 33
Expando 4 33
Different Delete Messages 7 10
OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

771 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now