我正在使用 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>
关于c# - 使用 Ajax 从 Controller 返回 String[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18695448/