1

我正在使用 Ajax 在我的 MVC 控制器上调用一个方法。我希望它返回一个string[]. 如何在 Ajax/MVC 中实现这一点?

我需要先将其转换为 JSON 对象吗?如果是这样,我该怎么做?

谢谢

4

2 回答 2

4

在 ASP.NET 中,您可以编写一个简单的控制器,如下所示:

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

然后你可以调用它,http://hostname/controllerName/GetStringArray输出将是["a","b","d"]

如果您想发出 GET 请求,请务必JsonRequestBehavior.AllowGet在转换时最后添加。

通过使用像 jQuery 这样的框架,您可以轻松地填充下拉列表。

<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>
于 2013-09-09T09:46:20.393 回答
2

您可以使用您可能需要的任何参数返回 JSON。创建一个像下面这样的动作

public JsonResult AjaxHandler(string SomeParam)
{
    return Json(new{
            someOtherDataId = 3,
            stringArray = 
                new string[] {"one", "two", "three", "four"}
        },
    JsonRequestBehavior.AllowGet);
}
于 2013-09-09T09:45:44.780 回答