2

is it possible to read the contents of an array that is passed from an MVC Controller to JavaScript?

This is a method in my controller that returns an array. (tried with a list before but didn't succeed)

public string[] GetAllEvents() 
{
    string[] array = new string[2];
    array[0] = "a";
    array[1] = "b";

    List<string> lst = new List<string>();
    lst.Add("a");
    lst.Add("b");
    return array;
}

Here is the JavaScript function from which I'm calling the Controller method.

function GetAllEvents() {
    $.ajax({
        type: "GET",
        url: "/Service/GetAllEvents",
        success: function (result) {
            alert(result.toString() + "  " + result[0]);
        },
        error: function (req, status, error) {
            //alert("Error");
        }
    });
};

The result is a System.String[] and the result[0] is giving me 'S' as a result.

1
  • 1
    The result you see is probably actually the string "System.String[]", and result[0] is the character at index 0 in that string, hence the "S". Follow SLaks' answer and you should see expected results. Commented Apr 18, 2012 at 16:36

1 Answer 1

4

MVC actions should return ActionResults.

You can then return Json(list, JsonRequestBehavior.AllowGet) and it will work.

Sign up to request clarification or add additional context in comments.

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.