我如何使用字符串参数来区分命名空间或类型? [英] How can I use a string argument to case a namespace or type?

查看:221
本文介绍了我如何使用字符串参数来区分命名空间或类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在.NET 2.0的C#脚本的一些JSON输出。我们的目标是使用一种方法来输出所有的JSON饲料,我需要。所有型号都有相同的id和name属性,所以我有相同的部分在这里约15命名空间。总之:因为我用的城堡,我可以像调用该函数:

  /public/get_place_tags.castle
/public/get_place_types.castle
/public/get_place_whichEver.castle
 

其中在城堡调用每个方法,即: get_place_tags(){} ,但我想不会有工作在那里我可以调用一种方法来获得输出每一种类型是这样的:

  /public/get_json.castle?wantedtype=place_types
 

有谁知道如何解决这个问题?

 命名空间campusMap.Controllers
{
    [布局(家)
    公共类PublicController:BaseController
    {
        / *作品和收益* /
        公共无效get_pace_type()
        {
            CancelView();
            CancelLayout();

            place_types []类型= ActiveRecordBase< place_types> .FindAll();
            名单< JsonAutoComplete> type_list =新的名单,其中,JsonAutoComplete>();

            的foreach(在类型place_types place_type)
            {
                JsonAutoComplete OBJ =新JsonAutoComplete();

                obj.id = place_type.place_type_id;
                obj.label = place_type.name;
                obj.value = place_type.name;

                type_list.Add(OBJ);
            }

            JSON字符串= JsonConvert.SerializeObject(type_list);
            RenderText(JSON);
        }

        / *可以;吨曾经发现命名空间* /
        公共无效get_json(字符串wantedtype)
        {
            CancelView();
            CancelLayout();
            类型t = Type.GetType(wantedtype);

            T [] all_tag = ActiveRecordBase< T> .FindAll();
            名单< JsonAutoComplete> tag_list =新的名单,其中,JsonAutoComplete>();

            的foreach(在all_tag T标记。)
            {
                JsonAutoComplete OBJ =新JsonAutoComplete();

                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;

                tag_list.Add(OBJ);
            }

            JSON字符串= JsonConvert.SerializeObject(tag_list);
            RenderText(JSON);
        }
    }
}
 

- (最新理念)运​​行时类型的创作。这我觉得是一种方式来获得它的工作...-----最干净的想法

所以,我们的目标是真的有在运行时使用..权的类型..所以我认为这是可行的。 的http://www.java2s.com/$c$c/CSharp/Development-Class/Illustratesruntimetypecreation.htm 和基于的是,这里是迄今为止方法。我仍然有得到问题 T 让过去的错误 类型或命名空间名称'T'找不到(是否缺少using指令或程序集引用?)..不知道我要去哪里错在这里。似乎无法得到任何的它的工作笑..

 公共无效get_json(字符串类型)
{
    CancelView();
    CancelLayout();
    如果(String.IsNullOrEmpty(TYPE))
    {
        TYPE =place_types;
    }
    //获取当前的AppDomain
    AppDomain中的广告= AppDomain.CurrentDomain;

    //创建一个新的动态组装
    的AssemblyName的=新的AssemblyName();
    an.Name =DynamicRandomAssembly;
    AssemblyBuilder AB = ad.DefineDynamicAssembly(一,AssemblyBuilderAccess.Run);

    //创建一个新的模块来保存code的组装
    ModuleBuilder MB = ab.DefineDynamicModule(RandomModule);

    //创建模块的类型
    TypeBuilder TB = mb.DefineType(TYPE,TypeAttributes.Public);

    //完成创建类型,并使其可用
    类型t = tb.CreateType();
    T [] all_tag = ActiveRecordBase< T> .FindAll();

    名单< JsonAutoComplete> tag_list =新的名单,其中,JsonAutoComplete>();
    的foreach(在all_tag T标记。)
    {
        JsonAutoComplete OBJ =新JsonAutoComplete();
        obj.id = tag.id;
        obj.label = tag.name;
        obj.value = tag.name;
        tag_list.Add(OBJ);
    }
    RenderText(JsonConvert.SerializeObject(tag_list));
}
 

- (旧的想法)评估和演示code -----

所以这次尝试做到这一点是使用反射和东西做各种各样在此基础上的 HTTP://www.$c$cproject.com/script/Articles/ViewDownloads.aspx援助= 11939

 命名空间EvalCS code
{
    ///<总结>
    ///可以通过远程应用程序域边界运行界面。
    ///< /总结>
    公共接口IRemoteInterface
    {
        对象调用(字符串lcMethod,对象[]参数);
    }


    ///<总结>
    ///工厂类来创建对象暴露IRemoteInterface
    ///< /总结>
    公共类RemoteLoaderFactory:MarshalByRefObject的
    {
        私人常量的BindingFlags BFI = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;

        公共RemoteLoaderFactory(){}

        ///<总结>工厂方法来创建指定其名称的类型的实例,
        ///使用指定的程序集文件和最匹配指定参数的构造函数。 < /总结>
        ///< PARAM NAME =assemblyFile>包含其中命名的typeName类型寻求一个组件的文件的名称。 < /参数>
        ///< PARAM NAME =typeName的>的preferred类型的名称。 < /参数>
        ///< PARAM NAME =constructArgs>匹配在数量,顺序和类型的构造函数的参数来调用,或空的默认构造函数参数数组。 < /参数>
        ///<返回>返回值是psented作为ILiveInterface创建的对象重新$ P $。 < /回报>
        公共IRemoteInterface创建(字符串assemblyFile,字符串typeName的,对象[] constructArgs)
        {
            返程(IRemoteInterface)Activator.CreateInstanceFrom(
                assemblyFile,typeName的,假的,BFI,空,constructArgs,
                NULL,NULL,NULL).Unwrap();
        }
    }
}


#endregion
命名空间campusMap.Controllers
{

    公共类JsonAutoComplete
    {
        私人诠释编号;
        [JsonProperty]
        公众诠释ID
        {
            {返回标识; }
            集合{n =价值; }
        }
        私人字符串标签;
        [JsonProperty]
        公共字符串标签
        {
            {返回标签; }
            集合{标签=值; }
        }
        私人字符串值;
        [JsonProperty]
        公共字符串值
        {
            {返回值; }
            集合{值=价值; }
        }
    }


    [布局(家)
    公共类publicController:BaseController
    {
        #地区的JSON输出
        / *作品和收益* /
        公共无效get_pace_type()
        {
            CancelView();
            CancelLayout();
            place_types []类型= ActiveRecordBase< place_types> .FindAll();

            名单< JsonAutoComplete> type_list =新的名单,其中,JsonAutoComplete>();
            的foreach(在类型place_types place_type)
            {
                JsonAutoComplete OBJ =新JsonAutoComplete();
                obj.id = place_type.id;
                obj.label = place_type.name;
                obj.value = place_type.name;
                type_list.Add(OBJ);
            }
            JSON字符串= JsonConvert.SerializeObject(type_list);
            RenderText(JSON);
        }
        / *我怎么想它会工作有一个dynmaic类型* /
        公共无效get_json(字符串类型)
        {
            CancelView();
            CancelLayout();
            / * T [] all_tag = ActiveRecordBase< T> .FindAll();

            名单< JsonAutoComplete> tag_list =新的名单,其中,JsonAutoComplete>();
            的foreach(在all_tag T标记。)
            {
                JsonAutoComplete OBJ =新JsonAutoComplete();
                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;
                tag_list.Add(OBJ);
            } * /
            StringBuilder的jsonobj =新的StringBuilder();
            jsonobj.Append(+类型+[] all_tag = ActiveRecordBase<+类型+> .FindAll(); \ N);
            jsonobj.Append(名单,其中,JsonAutoComplete> tag_list =新的名单,其中,JsonAutoComplete>(); {\ N);
            jsonobj.Append(的foreach(+类型+,在all_tag标签){\ N);
            jsonobj.Append(JsonAutoComplete OBJ =新JsonAutoComplete(); \ N);
            jsonobj.Append(obj.id = tag.id; \ N);
            jsonobj.Append(obj.label = tag.name; \ N);
            jsonobj.Append(obj.value = tag.name; \ N);
            jsonobj.Append(tag_list.Add(OBJ); \ N);
            jsonobj.Append(} \ N);

            CSHARP codeProvider C =新CSHARP codeProvider();
            I codeCompiler ICC = c.CreateCompiler();
            CompilerParameters CP =新CompilerParameters();

            cp.ReferencedAssemblies.Add(system.dll中);
            cp.ReferencedAssemblies.Add(Newtonsoft.Json.Net20.dll);
            cp.ReferencedAssemblies.Add(Castle.ActiveRecord.dll);

            cp.CompilerOptions =/ T:库;
            cp.GenerateInMemory = TRUE;

            StringBuilder的SB =新的StringBuilder();
            sb.Append(命名空间CS codeEvaler {\ N);
            sb.Append(公共类CS codeEvaler {\ N);
            sb.Append(公共对象评估和演示code(){\ N);
            sb.Append(回归+ jsonobj +\ N);
            sb.Append(} \ N);
            sb.Append(} \ N);
            sb.Append(} \ N);

            CompilerResults CR = icc.CompileAssemblyFromSource(CP,sb.ToString());
            System.Reflection.Assembly A = cr.CompiledAssembly;
            对象o = a.CreateInstance(CS codeEvaler.CS codeEvaler);

            类型t = o.GetType();
            MethodInfo的MI = t.GetMethod(评估和演示code);

            对象S = mi.Invoke(0,NULL);

            JSON字符串= JsonConvert.SerializeObject(S);
            RenderText(JSON);
        } / ** /
        #endregion
   }
 

我知道有人建议,使用是没有必要。我知道,我不知道他们过的顶部,这也许就是水平的表现。但在这里,他们是为了什么,我认为会工作的正上方。

 使用系统;
System.Collections中使用;
使用System.Collections.Generic;
使用Castle.ActiveRecord;
使用Castle.ActiveRecord.Queries;
使用Castle.MonoRail.Framework;
使用Castle.MonoRail.ActiveRecordSupport;
使用campusMap.Models;
使用MonoRailHelper;
使用System.IO;
使用System.Net;
使用的System.Web;
使用NHibernate.Ex pression;
使用的System.Xml;
使用System.Xml.XPath;
使用System.Text.RegularEx pressions;
使用System.Text;
使用的System.Net.Sockets;
使用System.Web.Mail和;
使用campusMap.Services;


使用Newtonsoft.Json;
使用Newtonsoft.Json.Utilities;
使用Newtonsoft.Json.Linq;

使用系统codeDOM。
使用系统codeDom.Compiler。
使用的System.Reflection;
使用Microsoft.CSharp;
使用System.Reflection.Emit;
使用了System.Runtime.InteropServices;
使用System.Runtime.Remoting;
使用System.IO;
使用的System.Threading;
使用的System.Reflection;
 

解决方案

我累了,想和疲惫的这些方式,使之一。我和一个同事想出了这个用的解决方案。我做了2个文件。

Ijson_autocomplete.cs

 使用系统;
命名空间campusMap.Models
{
    公共接口Ijson_autocomplete
    {
        INT ID {获得;组; }
        字符串名称{获取;组; }
        串get_json_data();
    }
}
 

json_autocomplete.cs

 使用系统;
使用System.Data这;
使用System.Configuration;
使用的System.Web;
使用System.Web.Security中;
使用System.Web.UI程序;
使用System.Web.UI.WebControls;
使用System.Web.UI.WebControls.WebParts;
使用System.Web.UI.HtmlControls;
使用Castle.ActiveRecord;
使用System.Collections.Generic;
使用System.Data.SqlTypes;
使用Newtonsoft.Json;
使用Newtonsoft.Json.Utilities;
使用Newtonsoft.Json.Linq;



命名空间campusMap.Models
{

    公共类JsonAutoComplete
    {
        私人诠释编号;
        [JsonProperty]
        公众诠释ID
        {
            {返回标识; }
            集合{n =价值; }
        }
        私人字符串标签;
        [JsonProperty]
        公共字符串标签
        {
            {返回标签; }
            集合{标签=值; }
        }
        私人字符串值;
        [JsonProperty]
        公共字符串值
        {
            {返回值; }
            集合{值=价值; }
        }
    }
    公共类json_autocomplete< T>其中t:campusMap.Models.Ijson_autocomplete
    {

        虚拟公共字符串get_json_data()
        {
            T [] all_tag = ActiveRecordBase< T> .FindAll();
            名单< JsonAutoComplete> tag_list =新的名单,其中,JsonAutoComplete>();
            的foreach(在all_tag T标记。)
            {
                JsonAutoComplete OBJ =新JsonAutoComplete();
                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;
                tag_list.Add(OBJ);
            }
            返回JsonConvert.SerializeObject(tag_list);
        }
    }
}
 

然后当我打电话从URL这个功能是它最后成为

 公共无效get_json(字符串类型)
        {
            CancelView();
            CancelLayout();
            类型t = Type.GetType(campusMap.Models。+型);
            Ijson_autocomplete theClass描述=(Ijson_autocomplete)Activator.CreateInstance(T);
            RenderText(theclass.get_json_data());
        }
 

和一次性模型

 命名空间campusMap.Models
{
    [ActiveRecord的(懒惰= TRUE)]
    公共类place_types:json_autocomplete< place_types>中campusMap.Models.Ijson_autocomplete
    {
        私人诠释place_type_id;
        [PrimaryKey的(place_type_id)]
        虚拟公众诠释ID
        {
            {返回place_type_id; }
            集合{place_type_id =价值; }
        }

        私人字符串名称;
        [属性]
        虚拟公共字符串名称
        {
            {返回名称; }
            集合{名称=值; }
        }

        私人字符串的Attr;
        [属性]
        虚拟公共字符串ATTR
        {
            {返回的Attr; }
            集合{的Attr =价值; }
        }
        私人的IList<地方>地方;
        [HasAndBelongsToMany(typeof运算(场所),懒惰= TRUE,表=place_to_place_models,ColumnKey =place_model_id,ColumnRef =place_id,逆=真,NotFoundBehaviour = NotFoundBehaviour.Ignore)
        虚拟市民的IList<地方>地点
        {
            {返回的地方; }
            集合{地方=价值; }
        }

    }
}
 

现在,当你调用

  /public/get_json.castle?wantedtype=place_types
 

  /public/get_json.castle?wantedtype=place_tags
 

您会得到每个模型的JSON输出。田田! :D谢谢大家的帮助

I need to get some JSON output in a .NET 2.0 C# script. The goal is to use one method to output all the JSON feeds I need. All the models have the same id and name properties so I have about 15 namespaces that have the same parts here. In short: since I'm use castle I can call the function like:

/public/get_place_tags.castle
/public/get_place_types.castle
/public/get_place_whichEver.castle

Which in castle is calling each method, ie: the get_place_tags(){} but I want to not have to work where I can call one method to get output from each type like this:

/public/get_json.castle?wantedtype=place_types

Does anyone know how to fix this?

namespace campusMap.Controllers
{
    [Layout("home")]
    public class PublicController : BaseController
    {
        /*  works and returns */
        public void get_pace_type()
        {
            CancelView();
            CancelLayout();

            place_types[] types = ActiveRecordBase<place_types>.FindAll();
            List<JsonAutoComplete> type_list = new List<JsonAutoComplete>();

            foreach (place_types place_type in types)
            {
                JsonAutoComplete obj = new JsonAutoComplete();

                obj.id = place_type.place_type_id;
                obj.label = place_type.name;
                obj.value = place_type.name;

                type_list.Add(obj);
            }

            string json = JsonConvert.SerializeObject(type_list);
            RenderText(json);
        }

        /*  can;t ever find the namespace */
        public void get_json(string wantedtype)
        {
            CancelView();
            CancelLayout();
            Type t = Type.GetType(wantedtype); 

            t[] all_tag = ActiveRecordBase<t>.FindAll();
            List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();

            foreach (t tag in all_tag)
            {
                JsonAutoComplete obj = new JsonAutoComplete();

                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;

                tag_list.Add(obj);
            }

            string json = JsonConvert.SerializeObject(tag_list);
            RenderText(json);
        }
    }
}

[EDIT]-- (Newest Idea) Runtime type creation.. This I think is the cleanest idea on a way to get it to work...-----

So the goal is really to have at runtime a type used.. right.. so I thought this would work. http://www.java2s.com/Code/CSharp/Development-Class/Illustratesruntimetypecreation.htm and based of that here is the method so far. I'm still having issues getting t to get past the error "The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?)" .. not sure where I'm going wrong here. Can't seem to get any of it to work lol..

public void get_json(String TYPE)
{
    CancelView();
    CancelLayout();
    if (String.IsNullOrEmpty(TYPE))
    {
        TYPE = "place_types";
    }
    // get the current appdomain
    AppDomain ad = AppDomain.CurrentDomain;

    // create a new dynamic assembly
    AssemblyName an = new AssemblyName();
    an.Name = "DynamicRandomAssembly";
    AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);

    // create a new module to hold code in the assembly
    ModuleBuilder mb = ab.DefineDynamicModule("RandomModule");

    // create a type in the module
    TypeBuilder tb = mb.DefineType(TYPE, TypeAttributes.Public);

    // finish creating the type and make it available
    Type t = tb.CreateType();
    t[] all_tag = ActiveRecordBase<t>.FindAll();

    List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();
    foreach (t tag in all_tag)
    {
        JsonAutoComplete obj = new JsonAutoComplete();
        obj.id = tag.id;
        obj.label = tag.name;
        obj.value = tag.name;
        tag_list.Add(obj);
    }
    RenderText(JsonConvert.SerializeObject(tag_list)); 
}

[EDIT]-- (Older idea) Eval code-----

So this attempt to make this happen is to use reflection and stuff to do a eval of sorts based on this http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=11939

namespace EvalCSCode
{
    /// <summary>
    /// Interface that can be run over the remote AppDomain boundary.
    /// </summary>
    public interface IRemoteInterface
    {
        object Invoke(string lcMethod, object[] Parameters);
    }


    /// <summary>
    /// Factory class to create objects exposing IRemoteInterface
    /// </summary>
    public class RemoteLoaderFactory : MarshalByRefObject
    {
        private const BindingFlags bfi = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;

        public RemoteLoaderFactory() { }

        /// <summary> Factory method to create an instance of the type whose name is specified,
        /// using the named assembly file and the constructor that best matches the specified parameters. </summary>
        /// <param name="assemblyFile"> The name of a file that contains an assembly where the type named typeName is sought. </param>
        /// <param name="typeName"> The name of the preferred type. </param>
        /// <param name="constructArgs"> An array of arguments that match in number, order, and type the parameters of the constructor to invoke, or null for default constructor. </param>
        /// <returns> The return value is the created object represented as ILiveInterface. </returns>
        public IRemoteInterface Create(string assemblyFile, string typeName, object[] constructArgs)
        {
            return (IRemoteInterface)Activator.CreateInstanceFrom(
                assemblyFile, typeName, false, bfi, null, constructArgs,
                null, null, null).Unwrap();
        }
    }
}


#endregion
namespace campusMap.Controllers
{

    public class JsonAutoComplete
    {
        private int Id;
        [JsonProperty]
        public int id
        {
            get { return Id; }
            set { Id = value; }
        }
        private string Label;
        [JsonProperty]
        public string label
        {
            get { return Label; }
            set { Label = value; }
        }
        private string Value;
        [JsonProperty]
        public string value
        {
            get { return Value; }
            set { Value = value; }
        }
    }


    [Layout("home")]
    public class publicController : BaseController
    {
        #region JSON OUTPUT
        /*  works and returns */
        public void get_pace_type()
        {
            CancelView();
            CancelLayout();
            place_types[] types = ActiveRecordBase<place_types>.FindAll();

            List<JsonAutoComplete> type_list = new List<JsonAutoComplete>();
            foreach (place_types place_type in types)
            {
                JsonAutoComplete obj = new JsonAutoComplete();
                obj.id = place_type.id;
                obj.label = place_type.name;
                obj.value = place_type.name;
                type_list.Add(obj);
            }
            string json = JsonConvert.SerializeObject(type_list);
            RenderText(json);
        }
        /*  how I think it'll work to have a dynmaic type */
        public void get_json(string type)
        {
            CancelView();
            CancelLayout();
            /*t[] all_tag = ActiveRecordBase<t>.FindAll();

            List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();
            foreach (t tag in all_tag)
            {
                JsonAutoComplete obj = new JsonAutoComplete();
                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;
                tag_list.Add(obj);
            }*/
            StringBuilder jsonobj = new StringBuilder("");
            jsonobj.Append(""+type+"[] all_tag = ActiveRecordBase<"+type+">.FindAll();\n");
            jsonobj.Append("List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();{\n");
            jsonobj.Append("foreach ("+type+" tag in all_tag){\n");
            jsonobj.Append("JsonAutoComplete obj = new JsonAutoComplete();\n");
            jsonobj.Append("obj.id = tag.id;\n");
            jsonobj.Append("obj.label = tag.name;\n");
            jsonobj.Append("obj.value = tag.name;\n");
            jsonobj.Append("tag_list.Add(obj);\n");
            jsonobj.Append("}\n");

            CSharpCodeProvider c = new CSharpCodeProvider();
            ICodeCompiler icc = c.CreateCompiler();
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("system.dll");
            cp.ReferencedAssemblies.Add("Newtonsoft.Json.Net20.dll");
            cp.ReferencedAssemblies.Add("Castle.ActiveRecord.dll");

            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;

            StringBuilder sb = new StringBuilder("");
            sb.Append("namespace CSCodeEvaler{ \n");
            sb.Append("public class CSCodeEvaler{ \n");
            sb.Append("public object EvalCode(){\n");
            sb.Append("return " + jsonobj + "; \n");
            sb.Append("} \n");
            sb.Append("} \n");
            sb.Append("}\n");

            CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
            System.Reflection.Assembly a = cr.CompiledAssembly;
            object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");

            Type t = o.GetType();
            MethodInfo mi = t.GetMethod("EvalCode");

            object s = mi.Invoke(o, null); 

            string json = JsonConvert.SerializeObject(s);
            RenderText(json);
        }/**/
        #endregion
   }

I know it was suggested that the using is not needed.. I know I don't know them off the top and maybe that is level showing.. But here they are for what I think will work just above.

using System;
using System.Collections;
using System.Collections.Generic;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Queries;
using Castle.MonoRail.Framework;
using Castle.MonoRail.ActiveRecordSupport;
using campusMap.Models;
using MonoRailHelper;
using System.IO;
using System.Net;
using System.Web;
using NHibernate.Expression;
using System.Xml;
using System.Xml.XPath;
using System.Text.RegularExpressions;
using System.Text;
using System.Net.Sockets;
using System.Web.Mail;
using campusMap.Services;


using Newtonsoft.Json;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;

using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.IO;
using System.Threading;
using System.Reflection;

解决方案

I tired and tried and tired to so one of these ways. Me and an co-worker came up this with solution. I made 2 files.

Ijson_autocomplete.cs

using System;
namespace campusMap.Models
{
    public interface Ijson_autocomplete
    {
        int id { get; set; }
        string name { get; set; }
        String get_json_data();
    }
}

json_autocomplete.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Castle.ActiveRecord;
using System.Collections.Generic;
using System.Data.SqlTypes;
using Newtonsoft.Json;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;



namespace campusMap.Models
{

    public class JsonAutoComplete
    {
        private int Id;
        [JsonProperty]
        public int id
        {
            get { return Id; }
            set { Id = value; }
        }
        private string Label;
        [JsonProperty]
        public string label
        {
            get { return Label; }
            set { Label = value; }
        }
        private string Value;
        [JsonProperty]
        public string value
        {
            get { return Value; }
            set { Value = value; }
        }
    }
    public class json_autocomplete<t> where t : campusMap.Models.Ijson_autocomplete
    {

        virtual public String get_json_data()
        {
            t[] all_tag = ActiveRecordBase<t>.FindAll();
            List<JsonAutoComplete> tag_list = new List<JsonAutoComplete>();
            foreach (t tag in all_tag)
            {
                JsonAutoComplete obj = new JsonAutoComplete();
                obj.id = tag.id;
                obj.label = tag.name;
                obj.value = tag.name;
                tag_list.Add(obj);
            }
            return JsonConvert.SerializeObject(tag_list);
        }
    }
}

then when I called the function from the url this is what it ended up as

        public void get_json(String TYPE)
        {
            CancelView();
            CancelLayout();
            Type t = Type.GetType("campusMap.Models."+TYPE);
            Ijson_autocomplete theclass = (Ijson_autocomplete)Activator.CreateInstance(t);
            RenderText(theclass.get_json_data());
        }

and one off the models

namespace campusMap.Models
{
    [ActiveRecord(Lazy=true)]
    public class place_types : json_autocomplete<place_types>, campusMap.Models.Ijson_autocomplete
    {
        private int place_type_id;
        [PrimaryKey("place_type_id")]
        virtual public int id
        {
            get { return place_type_id; }
            set { place_type_id = value; }
        }

        private string Name;
        [Property]
        virtual public string name
        {
            get { return Name; }
            set { Name = value; }
        }

        private string Attr;
        [Property]
        virtual public string attr
        {
            get { return Attr; }
            set { Attr = value; }
        }
        private IList<place> places;
        [HasAndBelongsToMany(typeof(place), Lazy = true, Table = "place_to_place_models", ColumnKey = "place_model_id", ColumnRef = "place_id", Inverse = true, NotFoundBehaviour = NotFoundBehaviour.Ignore)]
        virtual public IList<place> Places
        {
            get { return places; }
            set { places = value; }
        }

    }
}

now when you call

/public/get_json.castle?wantedtype=place_types

or

/public/get_json.castle?wantedtype=place_tags

You will get the json output of each model. Tada! :D Thank you everyone for helping.

这篇关于我如何使用字符串参数来区分命名空间或类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆