1

I'm using Ajax to call a method on my MVC controller. I want this to return a string[]. How do I achieve this in Ajax/MVC?

Do I need to convert it to a JSON object first? If so, how would I do this?

Thanks

3
  • asp.net-mvc and mvc are not the same. First one is framework, while latter one is a design-pattern. Commented Sep 9, 2013 at 9:44
  • @Leri but ASP.NET is a framework that based on MVC Commented Sep 9, 2013 at 9:44
  • @DaveJust How does it make them the same? Commented Sep 9, 2013 at 9:46

2 Answers 2

4

In ASP.NET you can write a simple controller like this:

public JsonResult GetStringArray()
{
    string[] d = {"a","b","d"};
    return Json(d, JsonRequestBehavior.AllowGet);
}

And then you can just call it with http://hostname/controllerName/GetStringArray and the output will be ["a","b","d"]

If you want to make GET requests it's important to add JsonRequestBehavior.AllowGet at the end when converting.

By using a framework like jQuery you can then easily populate a drop down list.

<script src="~/Scripts/jquery.min.js"></script>
<select id="selectString"></select>
<script>
    $(document).ready(function () {
        $.getJSON("http://hostname/controllerName/GetStringArray", function (data) {
            $.each(data, function (index, text) {
                $('#selectString').append(
                    $('<option></option>').val(index).html(text)
                );
            });
        });
    });
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

I was close! Its a Monday morning and I'm too sleepy for this :) Thanks for the quick and accurate response
2

you can return JSON with whatever parameters you may need. Create an action like the one bellow

public JsonResult AjaxHandler(string SomeParam)
{
    return Json(new{
            someOtherDataId = 3,
            stringArray = 
                new string[] {"one", "two", "three", "four"}
        },
    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.