Reputation: 469
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.
Upvotes: 1
Views: 3003
Reputation: 29674
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]);
});
}
Upvotes: 3
Reputation: 8275
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);
}
Upvotes: 0