namevaluecollectionconverter.cs
来自「AJAX开发工具包」· CS 代码 · 共 122 行
CS
122 行
using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
namespace AjaxPro
{
/// <summary>
/// Provides methods to serialize and deserialize a NameValueCollection.
/// </summary>
public class NameValueCollectionConverter : IJavaScriptConverter
{
private string clientType = "Ajax.Web.NameValueCollection";
public NameValueCollectionConverter() : base()
{
}
public override string GetClientScript()
{
return @"addNamespace(""Ajax.Web"");
Ajax.Web.NameValueCollection = function()
{
this.__type = ""System.Collections.Specialized.NameValueCollection"";
this.add = function(key, value) {
if(this[key] == null) {
this[key] = value;
}
}
this.getKeys = function() {
var keys = [];
for(key in this)
if(typeof this[key] != ""function"")
keys.push(key);
return keys;
}
this.getValue = function(key) {
return this[key];
}
this.toJSON = function() {
var o = this;
o.toJSON = null;
delete o.toJSON;
return AjaxPro.toJSON(o);
}
}
";
}
public override object Deserialize(IJavaScriptObject o, Type t)
{
if(!typeof(NameValueCollection).IsAssignableFrom(t) || !(o is JavaScriptArray))
throw new NotSupportedException();
JavaScriptArray a = (JavaScriptArray)o;
NameValueCollection list = (NameValueCollection)Activator.CreateInstance(t);
foreach(JavaScriptObject item in a)
{
list.Add(item.Keys[0], item[item.Keys[0]].ToString());
}
return list;
}
public override string Serialize(object o)
{
if(!(o is NameValueCollection))
throw new NotSupportedException();
StringBuilder sb = new StringBuilder();
NameValueCollection list = (NameValueCollection)o;
bool b = true;
sb.Append("new ");
sb.Append(clientType);
sb.Append("([");
for(int i=0; i<list.Keys.Count; i++)
{
if(b){ b = false; }
else{ sb.Append(","); }
sb.Append('{');
sb.Append(JavaScriptSerializer.Serialize(list.Keys[i]));
sb.Append(':');
sb.Append(JavaScriptSerializer.Serialize(list[list.Keys[i]]));
sb.Append('}');
}
sb.Append("])");
return sb.ToString();
}
public override Type[] SerializableTypes
{
get
{
return new Type[]{typeof(NameValueCollection)};
}
}
public override Type[] DeserializableTypes
{
get
{
return new Type[]{typeof(NameValueCollection)};
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?