0

从 json 中检索代码。

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?

4

1 回答 1

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);
    }
},
于 2012-07-05T06:09:36.430 回答