简体   繁体   English

从AJAX传递字符串到ASP.NET C#代码背后

[英]Passing string from AJAX to ASP.NET C# code behind

I am new to JS, even less experienced at AJAX. 我是JS的新手,即使对AJAX经验不足。 I'm just trying to pass a value to the code behind and return an expanded response. 我只是想将一个值传递给后面的代码并返回扩展的响应。 The problem is that despite the call succeeding, the string value passed from AJAX to C# is never anything other than "undefined", and it is driving me insane. 问题是,尽管调用成功,但从AJAX传递到C#的字符串值只不过是“ undefined”,这使我发疯。

The JS JS

function test() {
var message = "this is a test" ;
Display(message);}

function Display(words) {    
var hummus = { 'pass': words};
$.ajax({
    type: 'POST',
    url: 'Account.aspx/ShowMe',
    data: hummus,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',        
    success: function (response) {
        alert("Your fortune: " + response.d);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
       alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words + "\n\nError: " + lion);
    }    
});}

The Code Behind 背后的代码

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(string pass)
{
    string beans = pass + ". We repeat this is only a test.";

    return beans;
}

The end result is invariably "Your fortune: undefined. We repeat this is only a test." 最终结果总是“您的运势:不确定。我们重复这仅是一次考验”。 I would only like to know what I am missing. 我只想知道我在想什么。 Yes this is probably a stupid question but my searches reveal nothing helpful. 是的,这可能是一个愚蠢的问题,但我的搜索没有任何帮助。

Your issue is that you are trying to accept a string in your method public static string ShowMe(string pass) but you are passing a JavaScript object as your data. 您的问题是,您正在尝试在方法的public static string ShowMe(string pass)接受一个字符串,但是您正在将JavaScript对象作为数据传递。 See when you make an Ajax call ASP.Net will do its best to match up the data you posted to the type you have in your parameter - called Model Binding. 看看何时进行Ajax调用ASP.Net会尽力将发布的数据与参数(称为模型绑定)中的类型进行匹配。 When this cannot be achieved then you get an null passed in. 如果无法实现,则会传入一个null。

So in your JavaScript you are passing a JavaScript object using this: 因此,在您的JavaScript中,您将使用以下方法传递JavaScript对象:

var hummus = { 'pass': words};
$.ajax({
    ....,
    ....,
    data: hummus,

If you wish to post an object then your controller/method needs to have a C# model (class) that your JS will be bound to. 如果要发布对象,则您的控制器/方法需要具有JS绑定到的C#模型(类)。

So change your method to accept a model: 因此,更改您的方法以接受模型:

// somewhere in your code put this little model
// this is what your JavaScript object will get bound to when you post
public MyModel{
   // this is to match the property name on your JavaScript  object, its case sensitive i.e { 'pass': words};
   public string pass {get;set;} 
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(MyModel model)
{
    // you can now access the properties on your MyModel like this
    string beans = model.pass + ". We repeat this is only a test.";    
    return beans;
}

I found two issues in your code - 我在您的代码中发现了两个问题-

  1. Missing data: JSON.stringify(hummus), 缺少data: JSON.stringify(hummus),
  2. Remove lion which variable doesn't exist. 删除不存在该变量的狮子。

Fix 固定

function test() {
    var message = "this is a test";
    Display(message);
}

function Display(words) {
    var hummus = { 'pass': words };
    $.ajax({
        type: 'POST',
        url: 'Account.aspx/ShowMe',
        data: JSON.stringify(hummus), // Missing JSON.stringify
        contentType: 'application/json; charset=utf-8',
        dataType: 'json', 
        success: function (response) {
            alert("Your fortune: " + response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // remove lion which variable doesn't exist.
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words);
        }
    });
}

Working code 工作代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Account.aspx.cs" Inherits="WebApplication1.Account" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <button type="button" onclick="test()">Display Word</button>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

        <script type="text/javascript">

            function test() {
                var message = "this is a test";
                Display(message);
            }

            function Display(words) {
                var hummus = { 'pass': words };
                $.ajax({
                    type: 'POST',
                    url: 'Account.aspx/ShowMe',
                    data: JSON.stringify(hummus), // Missing JSON.stringify
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (response) {
                        alert("Your fortune: " + response.d);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        // remove lion which variable doesn't exist.
                        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words);
                    }
                });
            }

        </script>
    </form>
</body>
</html>


public partial class Account : System.Web.UI.Page
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string ShowMe(string pass)
    {
        string beans = pass + ". We repeat this is only a test.";

        return beans;
    }
}

Thank you both for your help. 谢谢你们的帮助。 I'm going to try the Model method, the JSON.stringify was something I had tried before and ultimately worked. 我将尝试使用Model方法,JSON.stringify是我之前尝试并最终成功的方法。

Apparently the problem I was not understanding how my browser worked. 显然问题是我不了解我的浏览器是如何工作的。 No matter what changes I made I was getting the same error. 无论我做了什么更改,我都会遇到相同的错误。 The reason? 原因?

My code wasn't in tags on the page, it was in a separate js file which Chrome was caching for me, effectively negating every change I made to try and correct the problem and driving me insane in the process. 我的代码不在页面上的标签中,而是在一个单独的js文件中,Chrome正在为我缓存该文件,有效地抵消了我为尝试解决该问题所做的所有更改,并在此过程中使我发疯。

In all I've learned a new technique, Model Binding, and that location of code can dramatically effect your Javascript experience. 总之,我已经学到了一种新的技术,即模型绑定,并且代码的位置可以极大地影响您的Javascript体验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM