ajax send FormData c# WebMethod
Asked Answered
Y

1

8

I have a form with a File Input and one Button, when I press the button the file should go to the server side.

When I send a file to the server the ajax response is success, never stop in the c# webmethod breakpoint that I use. What I am doing wrong?

The Form: (Default.aspx)

<form id="form1" runat="server" enctype="multipart/form-data">
    <div align="center" class="divBody">
        <div id="controlHost">
            <div id="outerPanel">
                <table width="100%" cellpadding="2" cellspacing="5">
                    <tr align="left">
                        <td colspan="2">
                            <span class="message">Seleccione el archivo que desea subir</span>
                        </td>
                    </tr>
                    <tr align="left">
                        <td valign="top">
                            <input type="file" id="FileInput" multiple="false" class="fileInput" />
                        </td>
                        <td align="right">
                            <input type="button" id="btnUpload" name="btnUpload" value="Upload" onclick="sendFile();" class="button" />
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</form>

The Script: (Default.aspx)

function sendFile() {
    var data = new FormData();
    var file = $("#FileInput")[0].files[0];
    data.append("name", file.name);
    data.append("size", file.size);
    data.append("type", file.type);
    data.append("file", file);

    $.ajax({
            type: "POST",
            async: true,
            url: "Default.aspx/UploadBlock",
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                alert("Success: " + result);
            },
            error: function (xhr, status) {
                alert("An error occurred: " + status);
            }
        });
};

The WebMethod: (Default.aspx.cs)

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Respuesta UploadBlock()
{
  Respuesta res = new Respuesta { Success = true, Message = "OK" }; //Break point here
  return res;
}

Thanks.

Yardman answered 16/11, 2016 at 21:4 Comment(10)
Does the return call hit error block ?Temperature
No, the return is successYardman
instead of alert write console.log(result) and see if the object has any properties.Claudeclaudel
@IvanArias: Do you have another method with the same name UploadBlock which accepts a parameter ?Temperature
Obviously since the Ajax call is successful, at least the web server is responding with a HTTP code indicating success. If it won't stop at the breakpoint, then you probably have another method which is being invoked.Gogetter
@Claudeclaudel The result is the page codeYardman
@Temperature No, I don't have another method with that nameYardman
@Ivan Arias found any solution? If you got solution then please share with us.Punjabi
@sandeepnagabhairava emmm... no, at the end I don't have other way that use an external MVC page that do that process and then there works everything, sorryYardman
@Gogetter Thank you!!! I've had exactly the same problem, and your answer pointed me to put a breakpoint at Page Load, where it was hit containing all my form data!Estus
J
3

In case someone comes across this as I did...

WebMethods expect a content-type of application/json - https://mcmap.net/q/1472421/-unable-to-call-server-side-webmethod-function

If you set the content-type to false, the ajax call will not hit your webmethod, it will go to page_load. There seems to be some other ways of accomplishing a file upload via stringifying the file but I was unable to get a working solution, so I simply created an HttpHandler (.ashx) file, compiled, and added the reference in web.config.

Using a handler, you can set the content-type to "false" in your ajax call and not have any problems. I sent the information as FormData, and it was easily consumed in the handler using context.Request.Files and context.Request

snippet of ajax call:

var fileControl = $("#file")[0].files[0];
var formData = new FormData();
formData.append("employeeId", employeeId);
formData.append("userfile", fileControl);
formData.append("filetype", uploadTypeSelect.val());

$.ajax({
                        type: "POST",
                        contentType: false,
                        url: "/Handlers/MyUploadHandler.ashx",
                        processData: false,
                        data: formData,
                        success: function (msg) {
                            //do something
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            //do something
                        }
                    });

Snippet of handler:

public override async Task ProcessRequestAsync(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var uploadedFile = context.Request.Files[0]; //only uploading one file
            var fileName = uploadedFile.FileName;
            var fileExtension = uploadedFile.ContentType;
            var folder = "MyOneDriveFolder";

            //this is an method written elsewhere to upload a file to OneDrive
            var uploaded = await OneDriveUpload.UploadDocument(filename,uploadedFile.InputStream, folderName, 0);

            context.Response.Write("Whatever you like");
        }
Jeremy answered 22/3, 2019 at 13:36 Comment(1)
you didn't covered how user can get data other than file that is passed in your jquery codeWinstead

© 2022 - 2024 — McMap. All rights reserved.