1

So I have this test method in my controller, in a C# MVC Project (using razor markup):

public virtual string[] TestArray(int id)
{
    string[] test = new string[] { "test1", "test2", "test3", "test4", "test5" };

    return test;
}

Is there any way to get this array into javascript?

Here is what I've tried:

function testArray(id) {
    $.get('Project/TestArray/' + id, function (data) {
        alert(data[0]);
    });
}

It goes without saying that this didn't work - I'm not great with javascript.

How can I correctly do what I'm describing?

NOTE: "Project" is the URL pattern for my Controller.

0

2 Answers 2

3

Return Json from your controller

public virtual ActionResult TestArray(int id)
{
    string[] test = new string[] { "test1", "test2", "test3", "test4", "test5" };

    return Json(test, JsonRequestBehavior.AllowGet);
}

Get a Json object in your js using getJSON

function testArray(id) {
    $.getJSON('Project/TestArray/' + id, function (data) {
        alert(data[0]);
    });
}
Sign up to request clarification or add additional context in comments.

6 Comments

This silently fails, are there any page includes / references I need?
No, just JQuery. Is it hitting your controller?
sounds like a routing issue. Fire up Fiddler or similar and confirm the HTTP request is being sent as you expect it to be. This is flagged as virtual also, are you overidding it anywhere?
Requests are being sent, but the request throws two 401's and a 404. Mysterious. Theres no overrides I'm aware of.
Wow, I just noticed, I was missing a '/' before 'Project'... it works perfectly now. Thanks a lot for your help (and patience) - it works like a charm now... /embarassment
|
0

Use instead an action returning a JSON element :

public JsonResult TestArray(int? id)
{
    string[] test = new string[] { "test1", "test2", "test3", "test4", "test5" };
    return Json(test, JsonRequestBehavior.AllowGet);
}

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.