如何将数据从 JSON 操作提取到视图中

本文关键字:提取 视图 操作 JSON 数据 | 更新日期: 2023-09-27 18:35:07

[HttpPost] 
public JsonResult searchByName(string name)
{
    dbCRMEntities dbx = new dbCRMEntities();
    var test = name;             
    var names = dbx.CONTACTS.Where(chk => name == chk.NAME);
    return this.Json(names, JsonRequestBehavior.AllowGet);    
}

此方法以以下格式返回数据:

[
    {
        "CONTACT_ID": 37,
        "NAME": "umair",
        "JOB_TITLE": "internee",
        "COMPANY": "fastservices",
        "PHONE": "244",
        "EMAIL": "umairliaquat@gmail.com",
        "WEB": "alskdjg",
        "ADDRESS": "lahore",
        "STATUS": "Inactive",
        "TAGS": "sdf",
        "LEAD_SOURCE": "partner",
        "BACKGROUND": "skldjga",
        "OWNER": "a",
        "BIRTHDAY": "2014-12-18",
        "EntityState": 2,
        "EntityKey": {
            "EntitySetName": "CONTACTS",
            "EntityContainerName": "dbCRMEntities",
            "EntityKeyValues": [
                {
                    "Key": "CONTACT_ID",
                    "Value": 37
                }
            ],
            "IsTemporary": false
        }
    }
]

我的jquery方法是:

$(document).ready(function () {
    $("#btn1").click(function () {
        var name = $("#search").val();
        //name = "ali";
        alert(name);
        $.post("/Status/searchByName", { name: name }, function (data) {
            document.write(data);
            $.each(data, function (key, value) {
            });
        }, "text");
    });
});

我想在视图中以表格形式获取数据。请指导我

如何将数据从 JSON 操作提取到视图中

需要将$.postdataType更改为'json'。然后jQuery将返回一个对象数组作为你的data参数。

现在在您的each中,第一个参数将被index,第二个参数将是单个对象

$.post("/Status/searchByName", { name: name }, function (data) {
        $.each(data, function (index, item) {               
               var rowData =[];
                rowData.push(item.CONTACT_ID);
                rowData.push(item.COMPANY);
                rowData.push(item.EntityKey.EntitySetName);
                 /* ETC */
                var row ='<tr><td>' + rowData.join('</td><td>') +'</td></tr>';
                $('table').append(row);
        });
    }, "json");
});

您还可以使用 $.each 遍历每个对象中的每个属性,如果它是原始值,则将其推送到 html 中

$.each(data, function (index, item) { 
     var rowData =[];
    $.each(item, function( key, value){
       if(typeof value !=='object'){
          rowData.push(value);
        }else if( key === 'EntityKey'){
           /* parse to data array*/
        }  
    });
    /* append to table as above */
});