能否讓客戶端和服務端操作同一json對象呢?目前想到的方式是通過客戶端隱藏控件來實現。
以下是一個泛型列表對象 List<TrainingImplement> ,轉為json後,客戶端和服務端如何操作
1、json對象與C#泛型相互轉換代碼
復制代碼 代碼如下:
//將json數據轉換為泛型
public static T ConvertByteDataToObject<T>(string byteData)
{
T obj;
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(byteData)))
{
var serializer = new DataContractJsonSerializer(typeof(T));
obj = (T)serializer.ReadObject(ms);
}
return obj;
}
//將泛型轉換為json
public static string ConvertObjectToByteData<T>(T obj)
{
string result;
using (var ms = new MemoryStream())
{
var serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(ms, obj);
ms.Position = 0;
result = Encoding.UTF8.GetString(ms.ToArray());
}
return result;
}
2、json數據源存入在客戶端隱藏控件中
復制代碼 代碼如下:
<input type="hidden" id="hideDataSource" runat="server" />
3、注意隱藏控件放json數據後,因為包含"/",會使request請示發生錯誤,所以頁頭請設置ValidateRequest="false"
復制代碼 代碼如下:
<%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true"
4、頁面加載Page_Load時,初始化json數據源
復制代碼 代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
#region 加載數據源
if (!IsPostBack)
{
List<TrainingImplement> list= new List<TrainingImplement> (){
new TrainingImplement (){
Code="aaa",
c_name ="bbb"
}
....
}//初始化數據源
hideDataSource.Value = ConvertObjectToByteData(list);
}
else
{
//如果是回傳,數據源從客戶端讀取
List<TrainingImplement> list = ConvertByteDataToObject<List<TrainingImplement>>(hideDataSource.Value);
hideDataSource.Value = ConvertObjectToByteData(list);
}
#endregion
4、客戶端js操作json數據源示例
復制代碼 代碼如下:
<script type="text/javascript" src="../Scripts/jquery-1.4.3.js"></script>
<script type="text/javascript" src="../Scripts/jquery-ui-1.8.7.custom.min.js"></script>
<script type="text/javascript" src="../Scripts/jquery.json-2.2.min.js"></script>
<script type ="text/javascript" >
var DataSourceHidName = "hideDataSource";
var dataSourceDom;
var dataSourceJson;
$(document).ready
(function () {
//獲取數據源
dataSourceDom = document.getElementById(DataSourceHidName);
dataSourceJson = eval("(" + dataSourceDom.value + ")");
});
//修改第1個TrainingImplement對象的Code值示例方法
function ModifiedCode() {
dataSourceJson[0]._code = "Code001";
//將更新值後的json對象重新寫入隱藏控件中
dataSourceDom.value = $.toJSON(dataSourceJson);
}
</script>
5、服務端C#操作Json數據源
復制代碼 代碼如下:
List<TrainingImplement> list = ConvertByteDataToObject<List<TrainingImplement>>(hideDataSource.Value);