【问题标题】:using $.GetJSON() function to retrieve an array of class objects使用 $.GetJSON() 函数检索类对象数组
【发布时间】:2015-02-20 08:13:47
【问题描述】:
我已经实现了一个 WEB API 2 控制器,它返回一个类对象的数组。现在,我想在我的 MVC 5 应用程序中使用这个 API。为此,我发现可以使用 getJSON 方法。但问题是我不知道如何从 getJSON 方法获取类对象数组。此外,根据返回的对象数量,我必须在 UI 上创建相等数量的网格。欢迎任何指针、链接或示例代码。
【问题讨论】:
标签:
asp.net-mvc-5
asp.net-ajax
getjson
asp.net-web-api2
【解决方案1】:
以下示例将帮助您使用 Web api 并在您的页面中使用该数据。
控制器:-
public class TestController : ApiController
{
public IEnumerable<temp> Get()
{
var context = new Test();
return context.temps;
}
}
用于数据库的模型和 DbContext 类:-
[Table("temp")]
public class temp
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(TypeName = "numeric")]
public decimal tempid { get; set; }
[Required]
[StringLength(50)]
public string name { get; set; }
[Required]
[StringLength(50)]
public string address { get; set; }
}
public class Test : DbContext
{
public Test()
: base("name=Test")
{
}
public virtual DbSet<temp> temps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<temp>()
.Property(e => e.tempid)
.HasPrecision(18, 0);
}
}
查看面:-
<html>
<head>
<script src="~/Scripts/js/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function()
{
$.getJSON("http://localhost:51197/api/Test", function (data) {
$.each(data, function (key, val) {
$("<table border='1'><tr><td>" + val.name + "</td><td>" + val.address
+ "</td></tr></table>").appendTo("#tbPerson");
});
});
});
</script>
</head>
<body>
<div id="tbPerson">
</div>
</body>
</html>
【解决方案2】:
我不知道这是否是您要查找的内容,但是在解析包含多个对象的 json 字符串时,您可以简单地使用每个对象。
在循环内部,您可以创建网格,因此您依赖于对象的数量。
$.each(jsonstring, function (i, object) {
/*create your grid and handle your object here*/
/*access attributes of your object with object.attributname*/
}
这就是你要找的吗?
【解决方案3】:
假设您尝试在 JavaScript 中使用 API。
有两种消费方式
- $.getJSON()
- $.ajax()
详情请查看:Difference Between $.getJSON() and $.ajax() in jQuery
JavaScript 非常开放、灵活并且本质上是面向对象的。
因此,您从上面得到的结果将是 JavaScript 对象,您可以使用相同的 via 循环来获得预期的结果。
function example() {
var data = [{ "Roll": "1", "Name": "A" }, { "Roll": "2", "Name": "B" }, { "Roll": "3", "Name": "C" }];
for (var index = 0; index < data.length; index++) {
var item = data[index];
// Play with your data item for eg
console.log(item.Roll);
console.log(item.Name);
}
// JSON being javascript object
// you can attach properties at run time too
data.Source = "AJAXCall Blah";
// Later in JS same can be used in appropriate scope.
console.log(data.Source);
};
$.each(dataReturnedFromAJAXCall,function(item){
// play with your data here
});
How do I iterate over a JSON structure?
http://www.w3schools.com/js/js_json.asp