1

I've searched all over looking at similar questions but unfortunately none seem to quite work for me.

What I'm doing: I have a main page with a link to upload a document. When that link is clicked it opens a modal window with a simple upload form:

<div id="uploadResults">
@using (Html.BeginForm("_uploadDocument", "Request", FormMethod.Post, new { id = "uploadDoc", enctype = "multipart/form-data" }))
 {
    <input name="eGuid" value="@ViewBag.eGuid" id="eGuid" type="hidden" />
    <input name="result" id="result" value="@ViewBag.result" type="hidden" />
    <label for="attachment">Attachment:</label><input type="file" name="attachment" id="attachment" />
    <br />
    <input type="submit" name="submit" value="Upload" class="txtButton" />
 }
</div>

On submit of the form I'd like to call my _uploadDocument method in the controller. If the upload succeeds then close the modal window so the parent window is again present. If there is an error then keep the modal window present and display some notification text.

My controller for the httppost (apologies, I've tried several methods and so you'll see a few commented out bits):

[HttpPost]
        public void _uploadDocument(string eGuid, HttpPostedFileBase attachment)
        {
            // store result txt
            string result = "";

            // check for uploaded file
            if (attachment != null && attachment.ContentLength > 0)
            {
                // get filename
                var uploadedFileName = Path.GetFileName(attachment.FileName);
                var newFileName = eGuid + "_" + uploadedFileName;

                // store to the shared directory
                var path = System.Web.Configuration.WebConfigurationManager.AppSettings["UploadDirectory"];
                var savePath = Path.Combine(path, newFileName);
                try
                {
                    attachment.SaveAs(savePath);
                    result = "success";
                }
                catch
                {
                    result = "There was an issue uploading your file";
                }
            }
            else
            {
                result = "No file was chosen for upload";
            }

            ViewBag.result = result;
            ViewBag.eGuid = eGuid;
            //return PartialView("_uploadDocument");
            //return Json(new { result = result});
            //return Json(result);
        }

Within my modal window, where the form above is, I have tried the following jquery:

$("#uploadDoc").submit(function (e) {
        $.post(this.action, { eGuid: $('#eGuid').val(), attachment: $('#attachment') }, function () {
            $("#dialog5").dialog('close');
            //alert("In");
            //return false;
        });
        //$.post(this.action, { eGuid: $('#eGuid').val(), attachment: $('#attachment') });
        return false;
    });

My results - if I serialize the data passed then the success function fires but the document isn't uploaded (so the modal window closes but no document is uploaded).

If I use the code as above then the document is uploaded but I'm taken to a blank white screen after submit...

I'd certainly appreciate any pointers!

UPDATE Here's the code opening the modal window from the parent page:

// person look-up modal window
    $(function () {
        $('#dialog5').dialog({
            autoOpen: false,
            width: 400,
            resizable: false,
            title: 'Upload Document',
            dataType: "json",
            modal: true,
            open: function (event, ui) {
                var updateArea = $(this).data('area');
                //alert(updateArea);
                $(this).load('@Url.Action("_uploadDocument", "Request")' + '?eGuid=' + updateArea);
            },
            cancel: function (event, ui) {
                $(this).dialog("close");
            }
        });

        $('.attachDocument').live("click", function () {
            var field = this.name;
            $('#dialog5').data('area', field).dialog('open');
        });
    });
Eddie Wesley
  • 149
  • 3
  • 16
  • My purpose for this is the parent window contains data that may not yet be saved (so I don't want a refresh/postback/etc). Maybe my approach is wrong - essentially I need a way to upload a document to the server without disrupting my parent form... – Eddie Wesley Aug 17 '12 at 16:32

2 Answers2

0

You cannot upload files via ajax without using html 5, iframe hacks, etc. It appears to me that your best bet would be to use an uploader such as uploadify or plupload.

Binding-httppostedfilebase-using-ajax-beginform is a similar question that has some good suggestions how to get around this.

Community
  • 1
  • 1
Josh Mein
  • 28,107
  • 15
  • 76
  • 87
  • I've certainly gotten that impression. I'll check your link - but I've seen other links that made me hopeful, such as this one: http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax – Eddie Wesley Aug 17 '12 at 16:27
  • I will try to look around some more. Let me know if you find anything out. – Josh Mein Aug 17 '12 at 16:32
0

It looks like you may have been on the right track, but abandoned it.

You can't issue a return statement properly from a void. Have you considered making your uploadDocument method a bool instead of void and returning the success state?

This way you could do something like:

$.post(this.action, { eGuid: $('#eGuid').val(), attachment: $('#attachment') }, function (data) {
  if(data == true) {
    $('#uploadResults').hide();
  }
});
Wesley
  • 5,381
  • 9
  • 42
  • 65
  • Thanks - I've tried so many different things that I can't be sure. I went ahead and the change to the control as a 'bool' and set the return values in addition to your changes above. Unfortunately this just takes me to a white screen with the word 'True' on it – Eddie Wesley Aug 17 '12 at 16:25
  • We're missing something int he code then. At some point there is a `Respose.Redirect` firing or something. Windows don't change on their own. Can we see more? – Wesley Aug 17 '12 at 16:30
  • Really the only other thing I can think of is the code that opens the modal window (from the parent page). If you think that will help I can post it – Eddie Wesley Aug 17 '12 at 16:34
  • Might as well. We've answered your question in the sense you can now properly communicate between your page and the server. I might post a new question specific to the unexpected behavior if we can't get it here. New questions that are more specific are more likely to get you better responses. Post it here first, though. I'll take a look. – Wesley Aug 17 '12 at 16:37
  • Thanks - I've updated the original post to include the modal display dialog – Eddie Wesley Aug 17 '12 at 16:40
  • What's odd is the function on success is never hit if the document actually posts... I've put in an alert box and it's never thrown. – Eddie Wesley Aug 17 '12 at 17:14
  • Exactly. Server Side something is changing the page even before the post completes. That's a separate question. I'd mark this one and ask another that is more specific as to why MvC is hijacking your session. – Wesley Aug 17 '12 at 18:19