Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does ASP.NET define JavaScript Converter

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

这篇"ASP.NET怎么定义JavaScript Converter"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"ASP.NET怎么定义JavaScript Converter"文章吧。

1、定义存在循环引用的类型

首先我们定义一个Boy类和Girl类以供使用:

public class Boy { public string Name; public Girl GirlFriend; } public class Girl { public string Name; public Boy BoyFriend; }

很显然,如果我将它们"配成一对",在序列化输出时就会抛出异常了。就冲着这点,我们就必须定义一个JavaScriptConverter啊,总不能拆散他俩。

2、定义JavaScriptConverter以及序列化能力

我们下面就该开始定义JavaScriptConverter了,我们姑且将其称之为BoyConverter。首先需要告诉ASP.NET,我们这个Converter可以支持哪些类型:

public class BoyConverter : JavaScriptConverter { public override IEnumerable SupportedTypes { get { yield return typeof(Boy); } } …… }

如果要实现一个比较良好的Serialize方法,就需要处理"有循环引用"和"没有循环引用"两种情况。幸运的是,对于Serialize方法来说,这点比较容易:

public override IDictionary, object, object = Dictionary, object = (Boy)obj; result["Name"] = boy.Name; // 如果有GirlFriend引用 if (boy.GirlFriend != null) { // 摘除循环引用 = ; result["GirlFriend"] = boy.GirlFriend; // 在客户端再建立关联 result["__getRealObject"] = "function(o) { = o; return o; }"; } return result; }

在这里,我们"手动"地将Boy对象转换为了一个IDictionary,这样就避免出现了循环引用。另外,为了在客户端直接得到一个互相引用的"Boy"和"Girl"对象

3、自定义序列化功能使用示例

那么我们来看一下使用示例吧,首先我们需要定义一个Web Service方法:

[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [Microsoft.Web.Script.Services.ScriptService] public class BoyGirlService : System.Web.Services.WebService { [WebMethod] public Boy GetBoy(string boyName, string girlName) { Boy boy = new Boy(); boy.Name = boyName; if (!String.IsNullOrEmpty(girlName)) { Girl girl = new Girl(); girl.Name = girlName; girl.BoyFriend = boy; boy.GirlFriend = girl; } return boy; } }以上就是关于"ASP.NET怎么定义JavaScript Converter"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report