通过 AJAX 向 ASP.NET WebMethod 传递多个参数时出现错误 302

发布于 2025-01-15 03:21:20 字数 1361 浏览 0 评论 0原文

我正在尝试在旧的 ASP.NET Web 应用程序(NET Framework 4.6.2 项目)中使用 AJAX 将三个参数传递给 WebMethod。

注意:我无法使用表单,因此三个控件(id、date 和 tempdocument)仅包含在

元素中(因此不在
中>)。

这是我的 javascript 代码:

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
    });
}

我试图在 webmethod 中捕获这些:

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

    // return some stuff in a Json result
}

运行 passValues() 时,我没有收到 javascript 错误,并且所有三个变量(id、date 和 filedata)都已填充,但是WebMethod 不会受到攻击。

然而,我确实收到了 302 网络错误(浏览器开发人员工具),但没有有关该错误的详细信息。

错误的原因是什么?是否可以在 ASP.NET 应用程序中使用 AJAX 传递文件?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

琉璃梦幻 2025-01-22 03:21:20

您的数据必须采用变量并形成一个字符串。

这样做可能需要一些混乱的 js 代码,但您可以使用 stringify,它会为您完成这项工作。我的意思是,当你使用 id : id 时,它如何知道“id”应该是“id”,或者 id 的值?你会得到哪一个?

因此,请尝试以下操作:

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

编辑:尝试构建测试网页

好的,因此当您构建 Web 方法时,您可以创建一个 Web 服务页面 (.asmx),或者您可以将 Web 方法直接拖放到(放置)到现有页面中。

因此,创建一个新网页 - 并测试/尝试添加 Web 方法。

假设您确实有 jQuery 工作(已安装),然后尝试创建一个新网页 - 并且不包含母版页(如果您使用它们)。

所以,你有一个看起来像这样的页面:

<%@ 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>

后面的代码看起来像这样:

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;
        }
    }
}

所以,尝试一个测试页面。

编辑#:获取 FileUpLoad 控件的值

您的代码看起来是错误的:

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

我看不到上面将如何工作???

这有效:

            <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>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文