Reputation: 97
I have a colorbox pop-up where I am displaying my view - UploadDocument. In this view I am having file upload element (type="file" ) and a textbox.
Here is the code for colorbox-
parent.parent.$.fn.colorbox({
href: url + '?callingWindow=' + window.frameElement.id,
open: true,
iframe: true,
width: "450px",
height: "300px",
title: "Upload Document",
close: '<button id=\"Save\">Save</button><button id=\"Cancel\">Cancel</button>',
onClosed: false
});
UploadDocument view is -
<h4 class="resume">Upload a document to presentation </h4>
<div class="description">Please click on the link below to add documents to your presentation.</div>
<table id="fieldsTable" class="tblFields">
<tr>
<td class="description">Choose file:</td>
<td> <input id="fileDialog" type="file" name="file"/></td>
</tr>
<tr>
<td class="description">Description:</td>
<td> <input type="text" id="docFileName" style="width: 225px;"/></td>
</tr>
<tr>
<td colspan="2" width="300px"><span class="errorMessage" id="spanErrorMessage"></span></td>
</tr>
</table>
On my view I am calling Post method of controller action on Save button's click.
<script type="text/javascript">
parent.$('#Save').click(function() {
$.ajax({
url: '@Url.Action("UploadDocument", "MyController")',
type: 'POST',
dataType: 'json',
cache: false,
data: { id: cmaId},
success: function () {
alert('added to temp');
}
});
});
</script>
Now when I call the action method UploadDocument with HttpPostedFileBase as a parameter. It is null all the time.
Is it because for this to work we have to have a tag and type=submit ? Since I can not do it here as Save button is not part of the view, but it's parent, is there any alternative for doing this with a normal button click and without any form tags ?
Upvotes: 3
Views: 5544
Reputation: 701
File uploads over an ajax call do not work like you seem to believe they do -- you simply can't post the form values like it's a standard form post with a few text boxes.
There are a couple of plugins out there that can help you out however, or depending on your requirements you can leverage FormData -- here's your code with formdata:
parent.$('#Save').click(function() {
var data = new FormData();
fd.append("id", cmaId);
fd.append("fileDialog", $("#fileDialog")[0]);
$.ajax({
url: '@Url.Action("UploadDocument", "MyController")',
type: 'POST',
dataType: 'json',
data: data,
contentType: false,
processData: false,
success: function () {
alert('added to temp');
}
});
});
I didn't run this, it's rough but it should give you enough to get started. If you are going to use jQuery with FormData then be aware that the contentType + processData options need to be set to false so jQuery doesn't alter your post data/headers.
Upvotes: 6