Skip to main content
 首页 » 编程设计

c#之使用 Ajax 从 Controller 返回 String[]

2024年01月28日36kenshinobiy

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

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

谢谢

请您参考如下方法:

在 ASP.NET 中,您可以像这样编写一个简单的 Controller :

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>