簡體   English   中英

從AJAX傳遞字符串到ASP.NET C#代碼背后

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

我是JS的新手,即使對AJAX經驗不足。 我只是想將一個值傳遞給后面的代碼並返回擴展的響應。 問題是,盡管調用成功,但從AJAX傳遞到C#的字符串值只不過是“ undefined”,這使我發瘋。

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

背后的代碼

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

    return beans;
}

最終結果總是“您的運勢:不確定。我們重復這僅是一次考驗”。 我只想知道我在想什么。 是的,這可能是一個愚蠢的問題,但我的搜索沒有任何幫助。

您的問題是,您正在嘗試在方法的public static string ShowMe(string pass)接受一個字符串,但是您正在將JavaScript對象作為數據傳遞。 看看何時進行Ajax調用ASP.Net會盡力將發布的數據與參數(稱為模型綁定)中的類型進行匹配。 如果無法實現,則會傳入一個null。

因此,在您的JavaScript中,您將使用以下方法傳遞JavaScript對象:

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

如果要發布對象,則您的控制器/方法需要具有JS綁定到的C#模型(類)。

因此,更改您的方法以接受模型:

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

我在您的代碼中發現了兩個問題-

  1. 缺少data: JSON.stringify(hummus),
  2. 刪除不存在該變量的獅子。

固定

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

工作代碼

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

謝謝你們的幫助。 我將嘗試使用Model方法,JSON.stringify是我之前嘗試並最終成功的方法。

顯然問題是我不了解我的瀏覽器是如何工作的。 無論我做了什么更改,我都會遇到相同的錯誤。 原因?

我的代碼不在頁面上的標簽中,而是在一個單獨的js文件中,Chrome正在為我緩存該文件,有效地抵消了我為嘗試解決該問題所做的所有更改,並在此過程中使我發瘋。

總之,我已經學到了一種新的技術,即模型綁定,並且代碼的位置可以極大地影響您的Javascript體驗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM