c#和Javascript操作同一json对象的实现代码
能否让客户端和服务端操作同一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;
}
<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
<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>
List<TrainingImplement> list = ConvertByteDataToObject<List<TrainingImplement>>(hideDataSource.Value);