呼叫web service取得JSON格式化資料
請問有什麼方法將其資料轉為DataTable並將數據顯示到GridView中?
更)現已將資料存成List
不過仍無法將List以GridView呈現:((出現錯誤訊息
我是VB寫法~你參考看看@@
https://ithelp.ithome.com.tw/questions/10202149
(啊我慣用Newtonsoft,真的比較好替資料塑形,高手炮小力一點)
1、不管你用EF5/6或DBML,一定會有個資料模型,阿就是資料庫的CLASS,如下為員工識別卡TABLE
public class V_EmpCardno
{
public string EmpNo { get; set; }
public string EmpCName { get; set; }
public string CardNo { get; set; }
public string 已離職 { get; set; }
public char EmpType { get; set; }
public string DeptCode { get; set; }
}
2、後端(asp.net)
protected void Page_Load(object sender, EventArgs e)
{
string act = Request.QueryString["act"];
if (!string.IsNullOrEmpty(act))
{
if (act == "hr")
{
HRDataContext myHR = new HRDataContext();
var data = myHR.V_EmpCardno.Where(p1 => p1.已離職 != "Y" && p1.CardNo.Trim() != "")
.OrderBy(o2 => o2.EmpNo)
.ToList<V_EmpCardno>();
Response.Clear();
Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(data));
Response.End();
}
}
}
前端程式(以Winform/為例)
void formload(){
var data = JsonConvert.DeserializeObject<List<V_EmpCardno>>(getWebResp("hr")); //下方有這個getWebResp函數的完整碼,示範只用到GET方式
foreach(var d in data.Where(p=>p.EmpCName.StartWith("陳")){
// ...... data已經是List,上行只列出姓陳的所有人員,用Lambda
Console.Writeline(d.EmpCName);
}
};
private string getWebResp(string v, string hostname = "www.yourcompany.com", List<KeyValuePair<string, string>> addKV = null)
{
string targetUrl = $"https://{mainHostName}/getdata?act={v}";
HttpWebRequest request = HttpWebRequest.Create(targetUrl) as HttpWebRequest;
request.Method = "GET";
request.ServerCertificateValidationCallback = delegate { return true; };
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 15000;
string result = "";
// 取得網站方的回應資料
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
}
}
}
catch (Exception e)
{
response.write($"錯誤發生:{e.Message}"
}
return result;
}