我在搜索引擎和 stackoverflow 中搜索我的问题的解决方案。我找到了很多答案,但没有一个对我有帮助。 这是我的 Controller :
[HttpGet]
public JsonResult Get()
{
var cl = new List<Category>();
cl.Add(new Category()
{
Name = "C#"
});
cl.Add(new Category()
{
Name = "MVC"
});
return Json(cl.ToList(),JsonRequestBehavior.AllowGet);
}
类别类别如下:
public class Category
{
public string Name { get; set; }
}
在我看来,我想列出数据中的每一项。
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: '@Url.Action("Get","Category")',
contentType: "application/json;charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function(data) {
//<ul>
//<li>C#</li>
//<li>MVC</li>
},
error: function () { alert('error....'); }
});
});
</script>
我该怎么做?
最佳答案
您可以使用较短的 getJSON
,如下所示:
var getUrl = '@Url.Action("Get")';
var resultDiv = $('#result');
$.getJSON(getUrl, data: { a: "testing"}, function (data) {
resultDev.append('<ul>')
$.each(data, function (index, item) {
resultDiv.append($('<li/>', { text: item.name }));
});
});
在没有看到您的标记的情况下,我假设输出到 div 只是为了演示目的。
关于c# - ASP.NET MVC 使用 ajax 从 Controller 获取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20162634/