我正在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>
如果有人知道,请帮助。提前致谢
答案 0 :(得分:1)
JavaScriptSerializer
未对私人字段进行序列化。在模型中将它们设为公共属性。
public class Defect
{
public string ID { get; set; }
public DateTime date_created { get; set; }
.... // etc
您的方法也期待收集所以它应该是
success: function (data) {
applychanges(data.dataList); // change
或者,更改控制器方法以返回集合
return Json(dataList, JsonRequestBehavior.AllowGet);
答案 1 :(得分:1)
请尝试使用以下内容替换GetFoodDetails。
function GetFoodDetails() {
$.ajaxSetup({
async: false
});
$.ajax({
type: 'GET',
url: '/Home/GetDetails',
success: function (data) {
alert(data.dataList);
}
});
}
如果有效,请告诉我,您的控制器操作方法代码没有变化。
你也可以试试这个
/* rows hidden by filtering (needed for child rows) */
.tablesorter .filtered {
display: none;
}