【发布时间】:2017-06-19 03:10:12
【问题描述】:
我正在 asp.net 中开发一个 web 应用程序,在索引页面中我实现了一个 AJAX 调用来获取缺陷对象列表并将其填充到 HTML 表中。
我在控制器“GetDefect”中编写了一个方法,它以 JSON 格式返回缺陷列表。但是当我在 Javascript 端得到它时,结果却是未定义的。
我已经花了几个小时,仍然找不到解决方案。我还搜索了其他 StackOverflow 问题,但无能为力。
模型类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication3.Models
{
public class Defect
{
private string ID;
private DateTime date_created;
private string updated_by;
private string created_by;
private string description;
public Defect(string ID, DateTime date_created,string updated_by,string ,created_by,string description)
{
this.ID = ID;
this.date_created = date_created;
this.updated_by = updated_by;
this.created_by = created_by;
this.description = description;
}
}
}
控制器
[HttpGet]
public JsonResult GetDefects()
{
IList<Defect> dataList = new List<Defect>();
dataList.Add(new Defect("eththeth",DateTime.Now.Date,"ergerger","ergergerger","ergerg"));
dataList.Add(new Defect("wefwefwef", DateTime.Now.Date, "wew44r3", "gbnvfbnvbn v", "gbndfgnbfgnf"));
return Json(new { dataList = dataList }, JsonRequestBehavior.AllowGet);
}
JS 文件
$(document).ready(function () {
GetFoodDetails();
});
function GetFoodDetails() {
$.ajax({
type: "GET",
url: "Home/GetDefects",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data.dataList);
applychanges(data);
},
error: function (response) {
alert('eror');
}
});
}
function applychanges(result) {
console.log(result);
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.ID + '</td>';
html += '<td>' + item.description + '</td>';
html += '<td>' + item.defect_status + '</td>';
html += '<td>' + item.date_created + '</td>';
html += '<td>' + item.created_by + '</td>';
html += '<td>' + item.location_lang + '</td>';
html += '<td>' + item.location_long + '</td>';
html += '<td><a href="#" onclick="return getbyID(' + item.ID + ')">Edit</a> | <a href="#" onclick="Delele(' + item.ID + ')">Delete</a></td>';
html += '</tr>';
});
$('.tbody').html(html);
}
HTML(表格)
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Date Raised</th>
<th>Date Due</th>
<th>Defect Status</th>
<th>Defect Remarks</th>
<th>Langitude</th>
<th>Longitude</th>
</tr>
</thead>
<tbody class="tbody">
</tbody>
</table>
如果有人知道,请帮忙。在此先感谢
【问题讨论】:
-
请edit您的问题显示浏览器收到的JSON。您应该能够在开发工具 Network 选项卡中看到它,或者如果没有,请在您的 Ajax 成功处理程序中添加
console.log(JSON.stringify(data))。 -
因为它们都是
private字段 - 将它们设为公共属性。 -
@StephenMuecke 它有效!非常感谢。
标签: javascript json ajax asp.net-mvc