2012-07-05 54 views
0

從json檢索代碼。從c#linq對象檢索數據到json到html

C#代碼: -

var collection = getsortcat.Select(x => new 
     { 
      idterm = x.IDTerm, 
      mvo = x.MVO, 
      pic = x.Pic, 
      said = x.SAid, 
      termactive = x.TermActive, 
      vid = x.Vid, 
      fvo = x.FVO, 
      eterm = x.ETerm, 
      edef = x.EDef, 
      buse = x.BUse, 
      bterm = x.BTerm, 
      idcat = x.TermCat, 
      items = x.TermCategory1.IDCat, 
      catname = x.TermCategory1.TermCategory1 
     }); 
     JavaScriptSerializer jss = new JavaScriptSerializer(); 
     string output = jss.Serialize(collection); 
     return Json(output, JsonRequestBehavior.AllowGet); 

的JavaScript代碼: -

success: function (e) { 
        var txt = "'{ data :" + e + "}'"; 
        var obj = eval("(" + txt + ")"); 
        $('#pdata').append(obj.data[0]); 
       }, 

沒有得到輸出。請給我解決方案如何檢索數據從C#linq對象到JSON到HTML?

回答

0

首先解決您的控制器操作以擺脫任何JavaScriptSerializers和手動管道代碼。直接收集返回JSON結果:

var collection = getsortcat.Select(x => new 
{ 
    idterm = x.IDTerm, 
    mvo = x.MVO, 
    pic = x.Pic, 
    said = x.SAid, 
    termactive = x.TermActive, 
    vid = x.Vid, 
    fvo = x.FVO, 
    eterm = x.ETerm, 
    edef = x.EDef, 
    buse = x.BUse, 
    bterm = x.BTerm, 
    idcat = x.TermCat, 
    items = x.TermCategory1.IDCat, 
    catname = x.TermCategory1.TermCategory1 
}); 
return Json(collection, JsonRequestBehavior.AllowGet); 

現在成功回調的e參數已經代表進行語法分析的對象的數組裏面。您無需致電eval。直接訪問元素(通過索引),然後屬性:

success: function (e) { 
    var txt = e[0].mvo; 
}, 

你也可以通過元素的循環:

success: function (e) { 
    for (var i = 0; i < e.length; i++) { 
     var element = e[i]; 
     alert(element.idterm); 
    } 
}, 
+0

任何理由downvote? –

+0

我爲你+1了。看起來對我來說是正確的答案。 –

+0

謝謝達丁先生。非常感謝。 –