gpt4 book ai didi

c# - 如何从 json 操作中获取数据到 View 中

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:09 25 4
gpt4 key购买 nike

[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");
});
});

我想在 View 中获取表格形式的数据。请指导我

最佳答案

需要将$.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 */
});

关于c# - 如何从 json 操作中获取数据到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27600553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com