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