0

I'm trying to pass three parameters to a WebMethod using AJAX in an old ASP.NET web application (NET Framework 4.6.2 project).

Note: I cannot use a form, so the three controls (id, date and tempdocument) are just wrapped in a <div> element (so not in <form>).

Here is my javascript code:

function passValues() {        
    // this one is from an <input> (text) control
    var date= $('#txbDate').val();

    // this one is from a <input> (date) control
    var id= $('#txbId').find('select').val();

    // this one is from an <input> (type=file) control
    var filedata = $("#TempDocument").get(0).files;

    // url to the aspx.file where the WebMethod is
    var url = 'Test.aspx/PassValues';
            
$.ajax({
    type: 'post',
    url: url,
    processData: false,
    contentType: false,
    data: { id: id, date: date, filedata: filedata}
    }).done(function (result) {

        // do some stuff here
    });
}

and I'm trying to catch these in a webmethod:

[WebMethod]
public static string PassValues(int id, string date, string filedata)
{
    // do some stuff here

    // return some stuff in a Json result
}

When running passValues() I get no javascript errors and All three variables (id, date and filedata) get populated, but the WebMethod does not get hit.

I do however get a 302 network error (browser developer tools) with no details about the error.

What is the reason for the error? Is it even possible to pass files with AJAX in an ASP.NET app?

TheMixy
  • 1,049
  • 15
  • 36

1 Answers1

0

Your data has to take the varibles and make a string.

It can be some messy js code to do that, but you can use stringify, and it will do the work for you. I mean, when you use id : id, how does it know that "id" supposed to be "id", or the value of id? Which will you get?

So, try this:

data: JSON.stringify({ id: id, date: date, filedata: filedata}),

Edit: Try building a test web page

Ok, so when you build a web method, you can create a web service page (.asmx), or you can drop (place) web methods right into a existing page.

so, create a new web page - and test/try adding a web method.

Assuming you do have jQuery working (installed) then try create a new web page - and don't include a master page (if you using them).

So, you have a page that looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Autocom.aspx.cs" Inherits="CSharpWebApp.Test2.Autocom" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="../Scripts/jquery-1.12.4.js"></script>
    <link href="../Content/bootstrap.css" rel="stylesheet" />
    <script src="../Scripts/bootstrap.js"></script>

    <style>
        input {border-radius:10px}
    </style>
</head>
<body>
    <form id="form1" runat="server">

        <div style="padding:25px">

    <h2>Celsius to Fahrenheit (°C to °F)</h2>
    <br />
    <div style="text-align:right;width:20%">
        <label style="font-size:large">Enter Celsious Tempature</label>
        <asp:TextBox ID="txtC" runat="server" style="font-size:large;margin-left:5px;text-align:center" 
            TextMode="Number" Width="80px" Wrap="False"
            ClientIDMode="Static">
        </asp:TextBox>
        <br /> <br />

        <div style="text-align:center">
            <asp:Button ID="cmdConvert" runat="server" Text="Convert to °F" CssClass="btn"
                OnClientClick="MyConvert();return false"/>
        </div>
        <br />
        <label style="font-size:large">Fahrenheit</label>
        <asp:TextBox ID="txtF" runat="server" style="font-size:large;margin-left:5px;text-align:center" 
            TextMode="Number"  Width="80px" Wrap="false"
            ClientIDMode="Static">
        </asp:TextBox>
    </div>

    <asp:FileUpload ID="FileUpload1" runat="server" />

    <script>
        function MyConvert() {
            txtC = $("#txtC");
            txtF = $("#txtF");
            $.ajax({
                type: "POST",
                url: "Autocom.aspx/ConvertToC",
                data: JSON.stringify({ MyC: txtC.val()}),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    txtF.val(msg.d);
                },
                error: function (xhr, status, error) {
                    var errorMessage = xhr.status + ': ' + xhr.statusText
                    alert('Error - ' + errorMessage)
                }
            });
        }
    </script>


        </div>
    </form>
</body>
</html>

And the code behind looks like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace CSharpWebApp.Test2
{
    public partial class Autocom : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static Double ConvertToC(Double MyC)
        {            
            Double CelResult = (MyC * 1.8) + 32;
            return CelResult;
        }
    }
}

So, try a test page.

Edit#: Getting value of a FileUpLoad control

Your code of this looks to be wrong:

var filedata = $("#TempDocument").get(0).files;

I Can't see how above will work????

This works:

            <asp:FileUpload ID="FileUpload1" runat="server" ClientIDMode="Static" />

            <asp:Button ID="Button1" runat="server" Text="check file up-load control"
                OnClientClick="checkmycontrol();return false"  />

    <script>
        function checkmycontrol() {
            var upload = $('#FileUpload1')
            alert(upload.val())
        }
    </script>
Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51
  • Tried it. The same error remains. – TheMixy Mar 21 '22 at 05:47
  • Then put in some console.log() commands in your js code - does it get the values BEFORE you call the web method? See my edit - post a working example of code. Keep in mind that the data{} passed must MATCH the parameter names used in your function in the code behind. So, can you get ANY ajax call working on ANY page, or does every single ajax call you have fail? Or is it just this one that don't work? Try my edit, and the posted example - does it work??? – Albert D. Kallal Mar 21 '22 at 14:24
  • What you have here works, but my code also works for simple parameters (strings, ints ...). Try adding a file (from file upload control) to this code and it doesn't work. – TheMixy Mar 22 '22 at 06:19
  • Just dropping in a FileUpLoad control should work just fine. I just dropped one in and page still works. FileUpLoad will need a post-back and and we not using one. Of course the code in code behind web method can't use controls or reference controls in code behind on the form (since no post back will have occurred), but that's a different issue then the page all of sudden not working anymore because I dropped in some additional controls. So dropping in say some check box control, a grid view, or FileUpLoad control will NOT change anything unless being used as part of this web call. – Albert D. Kallal Mar 22 '22 at 15:57
  • I just modified the posted markup - see the FileUpLoad control I dropped in - code still works. – Albert D. Kallal Mar 22 '22 at 15:58
  • See my edit #2 - I show how to get the value of a FiileUpLoad control - your posted code looks to be wrong - but has nothing to do with the ajax call not working - you simply trying to get a value of a control - and AS I STATED - put some console.log statements in your js code. But DO TAKE a look at my extra final edit - I show how to get the file name used in the FileUpLoad control. (I used staticID, since I hate using the other form of $("#<%=FileUpload1.ClientID%>") – Albert D. Kallal Mar 22 '22 at 16:20
  • I'm not sure how your code would function without a postback? There's nothing you changed in the code-behind Webmethod to accept some file data, also the ajax call remains the same as in your original post... ? – TheMixy Mar 23 '22 at 07:10
  • I am assuming there is not a post pack. with a ajax call, no such post-back is assumed to EVER have occurred. So, where and when is the post-back now occurring here? That is new information. I only posted the js code to get the current file that the user has selected with the fileupload control . However, at that point, no post-back has occurred. And in fact, if you do allow a post-back, then the file is up-loaded, and the file upload control is now cleared and empty anyway. So, where and when is some post-back occurring - that is new information. After post-back fileupload control is now gone – Albert D. Kallal Mar 23 '22 at 17:47
  • Gee, perhaps I did not make this issue clear. The file upload control cannot survive a post back. Any post-back will cause the file to up-load, and then when page round trip is done, the file upload control will be null and void. You get ONE post-back chance here. So any ajax call that attempts to look at or use the File Upload control has to occur before the post-back occurs. In effect, a button can be used to submit or post-back, but the js code and ajax call has to run and occur BEFORE the post-back, else use of the File Upload control is now gone and it will be empty. – Albert D. Kallal Mar 23 '22 at 18:43
  • Thank you, but I guess my question/comment were not clear enough. I want to send the file to the server via ajax call only (no classic postback). I'm not having any problems getting the file in javascript, my problem is sending it with ajax. Your sample code does not offer a solution. – TheMixy Mar 24 '22 at 06:14
  • You can get the file name is js - but the file data is a different matter. (and now that your goal is to get the file data - sure, my question don't help and you have to adopt code that implements a xhr - (and a post). So, file data is not available here - you have to write a custom bit of code. With a custom post method. – Albert D. Kallal Mar 24 '22 at 16:24
  • So, it cannot be done via ajax? – TheMixy Mar 25 '22 at 09:09
  • It can, but just not with a simple FileUPLoad control - since as I stated, it needs a post-back. Remember, there are HIGH restrictions on grabbing a file on a computer. Else when you come to look at my cat pictures site, I am going to rumange around on your computer and steal a file called passwords.txt, or steal outlook files, or steal files called banking. I use the FileUploader from the ajax tool kit, and there are others. You can use ajax - https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – Albert D. Kallal Mar 25 '22 at 13:59