1

I am new to JS, even less experienced at 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.

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

3 Answers 3

4

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. 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. When this cannot be achieved then you get an null passed in.

So in your JavaScript you are passing a JavaScript object using this:

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.

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

I found two issues in your code -

  1. Missing 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;
    }
}

Comments

0

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.

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.

In all I've learned a new technique, Model Binding, and that location of code can dramatically effect your Javascript experience.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.