Home  >  Article  >  Web Front-end  >  Implementation code for c# and Javascript to operate the same json object_javascript skills

Implementation code for c# and Javascript to operate the same json object_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:57:00851browse

Can the client and server operate on the same json object? The current way to think of it is to hide controls on the client side.
The following is a generic list object List. After it is converted to json, how does the client and server operate?
1. Conversion code between json objects and C# generics

Copy code The code is as follows:

//Convert json data to generics
public static T ConvertByteDataToObject(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;
}
//Convert generics to 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. The json data source is stored in the client hidden control
Copy code Code As follows:



3. Pay attention to the hidden control after placing json data , because including "/" will cause an error in the request request, so please set ValidateRequest="false" in the header of the page
Copy code The code is as follows:

<%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true"

4. When the page loads Page_Load, initialize json Data source
Copy code The code is as follows:

protected void Page_Load(object sender, EventArgs e)
{
#region Load data source
if (!IsPostBack)
{
List list= new List (){
new TrainingImplement (){
Code="aaa",
c_name ="bbb"
}
....
}//Initialize the data source
hideDataSource.Value = ConvertObjectToByteData(list);
}
else
{
//If it is a postback, the data source is read from the client
List list = ConvertByteDataToObject>(hideDataSource.Value);
hideDataSource.Value = ConvertObjectToByteData(list);
}
#endregion

4. Example of client js operation json data source
Copy code The code is as follows:





5. Server-side C# operates Json data source
Copy code The code is as follows:

List list = ConvertByteDataToObject>(hideDataSource.Value);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn