Json .NET 網頁傳接值

  • 405
  • 0
  • 2017-12-18

JS陣列轉成JSON後再被瀏覽器傳接轉成文字String

.NET(C#)接到文字後,再轉成JSON,物件化後直接取值

【需匯入 Newtonsoft.Json.dll 參考】

 

【需匯入 Newtonsoft.Json.dll 參考】

----------------------------------------------------
.NET read 轉成 json 格式
----------------------------------------------------

sql = @"SELECT * FROM MyTable";

cmd.CommandText = sql;
apt = new SqlDataAdapter(cmd);
dt = new DataTable();
apt.Fill(dt);

// 將 DataTable 轉 Json 字串
outJSONString = JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented);
// 回傳至前端
Response.Write(outJSONString);

----------------------------------------------------
【array to json 網頁傳送再被瀏覽器轉成 文字 string】
js array 轉成 json 格式,用Jqery傳值
----------------------------------------------------

//陣列
var obj = {};
obj.MyArray = [];
obj.MyArray.push({"Name":"John","Age":20});
obj.MyArray.push({"Name":"Judy","Age":20});
obj.MyArray.push({"Name":"JJJJ","Age":19});
obj.MyArray.push({"Name":"Jack","Age":22});
console.log(obj.MyArray);
//Json 格式,用ajax 傳送
var data = JSON.stringify(obj.MyArray);
console.log(data);
//Jquery 傳送
$.ajax({
	type: "POST",
	url: 'test.aspx',
	contentType: "application/json",
	Mydata: JSON.stringify({
		obj.MyArray
	}),
	success: function (rsp_data) {
		var obj = $.parseJSON(rsp_data);
		var cnt = obj.length;
		console.log(obj);
		for (var i = 0; i < cnt; i++) {
			var z = obj[i].zip;
		}
		//console.log("success");
	},
	error: function () {
		//console.log("error");
	}
});

----------------------------------------------------
【string to json】
.NET 接值
----------------------------------------------------

public class UpdateValue
{
	public string Name { get; set; }
	public string Age { get; set; }
}
string Name = "";
string Mydata = (Request.Form["Mydata"] == "" ? "" : Request.Form["Mydata"]);
List<UpdateValue> obj = JsonConvert.DeserializeObject<List<UpdateValue>>(Mydata);
foreach (UpdateValue RowData in obj)
{
	Name = RowData.Name;
	sql = @"Update MyTable ..... ";
	cmd = new SqlCommand(sql, con);
	cmd.ExecuteNonQuery();
}

 

當資料量少的時候,只要丟一個字串,可用下面方式:

JS 只傳送 apply_id 字串

.NET 接收

參考資料:

https://www.codeproject.com/Questions/1097722/Convert-json-string-to-object-in-webapi-using-Csha

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify