这个问题在这里已有答案:
如何使用Razor将未编码的Json写入我的View? 3个答案我想在javascript中使用我的C#列表。 我试过这些,但它不起作用;
服务器端:
List<TimeLine> myList= new List<TimeLine>(); TimeLine element= new TimeLine (); element.Name= "abc"; element.About= "ssss"; element.Id = id; myList.Add(element); System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); model.JSONList= oSerializer.Serialize(myList); return View(model);客户端:
$(function() { Draw(); }); function Draw() { var tunel = '@Model.JSONList'; var str = ""; if (tunel.length > 0) { for (var i = 0; i < tunel.length; i++) { str += '<span>'+tunel[i].Name+'</span>'+ '<span>'+tunel[i].Id+'</span>'+ '<span>'+tunel[i].About+'</span>'; } $("#myDiv").append(str); } }你能帮我把列表中的对象拿到JavaScript中吗?
谢谢。
注意:我也尝试过JSON.Parse('@ Model.JSONList'); 但它不起作用; 这是我的详细价值。 var tunel = JSON.parse('[{"Id":3,"Tarih":"\/Date(1425506400000)\/","Tip":2,"Hakkinda":"- Proje, görev, todo dökümlerini göster.","Adı":"Profil Ekranının Tasarlanması"},{"Id":26,"Tarih":"\/Date(1425160800000)\/","Tip":1,"Hakkinda":"Kişisel işlerin düzenlenmesi için geliştirilen proje.","Adı":"Kişisel Yazılım Asistanı"}]')
This question already has an answer here:
How do I write unencoded Json to my View using Razor? 3 answersI want to use my C# list in javascript. I tried these, but it doesnt work;
Server side:
List<TimeLine> myList= new List<TimeLine>(); TimeLine element= new TimeLine (); element.Name= "abc"; element.About= "ssss"; element.Id = id; myList.Add(element); System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); model.JSONList= oSerializer.Serialize(myList); return View(model);Client side:
$(function() { Draw(); }); function Draw() { var tunel = '@Model.JSONList'; var str = ""; if (tunel.length > 0) { for (var i = 0; i < tunel.length; i++) { str += '<span>'+tunel[i].Name+'</span>'+ '<span>'+tunel[i].Id+'</span>'+ '<span>'+tunel[i].About+'</span>'; } $("#myDiv").append(str); } }Can you help me to get the object in list and use it in JavaScript?
Thanks.
Note: I also tried JSON.Parse('@Model.JSONList'); but it doesnt work; Here is my detailed value. var tunel = JSON.parse('[{"Id":3,"Tarih":"\/Date(1425506400000)\/","Tip":2,"Hakkinda":"- Proje, görev, todo dökümlerini göster.","Adı":"Profil Ekranının Tasarlanması"},{"Id":26,"Tarih":"\/Date(1425160800000)\/","Tip":1,"Hakkinda":"Kişisel işlerin düzenlenmesi için geliştirilen proje.","Adı":"Kişisel Yazılım Asistanı"}]')
最满意答案
你需要解析你的JSON:
var tunel = JSON.parse('@Model.JSONList');否则你只是对字符串进行所有操作。
如果你是字符串出来编码(例如"而不是" ),那么你可以尝试使用@Html.Raw(Model.JSONList) :
var tunel = JSON.parse('@Html.Raw(Model.JSONList)');You need to parse your JSON:
var tunel = JSON.parse('@Model.JSONList');otherwise you're just doing all your operations on a string.
If you're string is coming out encoded (e.g. " instead of ") then you can try using @Html.Raw(Model.JSONList):
var tunel = JSON.parse('@Html.Raw(Model.JSONList)');更多推荐
发布评论