我有一个控制器正在返回objects
中的TempData
列表
public ActionResult timelineIndex()
{
var jsondata = new
{
data = (
from t in ptr.GetAll()
select (new
{
id = t.pptid,
Owner = t.Owner,
Duration = t.totaldays,
Comp = t.Status,
StartDate = t.StartDate,
EndDate = t.EndDate
}).ToString())
};
TempData["id"] = jsondata.data.ToList();
return View();
}
现在在视图中,我使用@html.Raw(json.Encode)
编码
var modeldata = @Html.Raw(Json.Encode(@TempData["id"])) ;
我想遍历所有我尝试过的对象,但是显示未定义。
console.log(modeldata);
var array = [];
array = modeldata;
for (var i = 0 ; i<11 ; i++) {
var obj = modeldata[i];
alert(obj.id);
alert(obj.Startdate)
}
对象的modeldata数组即将出现。
(11) ["{ id = 1, Owner = erewrwer, Duration = 7, Comp = e…w, StartDate = 2018-09-19, EndDate = 2018-09-26 }", "{ id = 2, Owner = erewrwer, Duration = 7, Comp = , StartDate = 2018-09-19, EndDate = 2018-09-26 }", "{ id = 3, Owner = erewrwer, Duration = 11, Comp = , StartDate = 2018-09-19, EndDate = 2018-09-30 }", "{ id = 4, Owner = erewrwer, Duration = 11, Comp = …z, StartDate = 2018-09-19, EndDate = 2018-09-30 }", "{ id = 5, Owner = erewrwer, Duration = 11, Comp = …z, StartDate = 2018-09-19, EndDate = 2018-09-30 }", "{ id = 6, Owner = erewrwer, Duration = 11, Comp = …z, StartDate = 2018-09-19, EndDate = 2018-09-30 }", "{ id = 7, Owner = erewrwer, Duration = 11, Comp = …S, StartDate = 2018-09-19, EndDate = 2018-09-30 }", "{ id = 8, Owner = erewrwer, Duration = 11, Comp = …S, StartDate = 2018-09-19, EndDate = 2018-09-30 }", "{ id = 9, Owner = erewrwer, Duration = 11, Comp = …E, StartDate = 2018-09-19, EndDate = 2018-09-30 }", "{ id = 10, Owner = erewrwer, Duration = -204, Comp…D, StartDate = 2018-11-30, EndDate = 2018-05-10 }", "{ id = 11, Owner = erewrwer, Duration = 6, Comp = …S, StartDate = 2018-09-24, EndDate = 2018-09-30 }"]
答案 0 :(得分:2)
您可以从c#代码中更正Javascript很好,它将正常工作
public ActionResult timelineIndex()
{
var jsondata = new
{
data = (
from t in ptr.GetAll()
select (new
{
id = t.pptid,
Owner = t.Owner,
Duration = t.totaldays,
Comp = t.Status,
StartDate = t.StartDate,
EndDate = t.EndDate
}))
};
TempData["id"] = jsondata.data.ToList();
return View();
}
答案 1 :(得分:-1)
您的数据格式不正确。它是JSON数据。您必须通过JSON.parse进行转换。这是工作示例。检查模型阵列。数据格式应如下所示。
let modelArray = [
{ id : 1, Owner : "erewrwer", Duration : 7, StartDate : "2018-09-19", EndDate : "2018-09-26" },
];
for (let i = 0; i < modelArray.length; i++) {
let obj = modelArray[i];
console.log('Object : ', obj);
console.log("Id : ", obj.id);
console.log("StartDate : ", obj.StartDate);
}