今天无意看到 Joyrock 及 JSON-RPC 关键字眼;貌似没听说过,搜索一下大概了解了一下。在网上找到了相关dll、js文件;并动手建了个web项目,写了个简单例子;以便看客直接进入实战。
图 - 1
新建项目,加入引用;闲话不唠了。还是直接代码了。
前端代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JoyrockWebDemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="JayrockDLL/json.js"></script>
<script type="text/javascript" src="JayrockHandler.ashx?proxy"></script>
<script type="text/javascript">
var jayrockHandler = new JayrockHandler();
function showData() {
//调用hander的GetHelloWord方法时,注意大小写(js敏感)
document.getElementById("helloWorld").innerHTML = jayrockHandler.GetHelloWorld();
document.getElementById("userList").innerHTML = jayrockHandler.GetUserList();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="Button1" type="button" value="showData" οnclick="showData();" />
<div id="helloWorld"></div>
<div id="userList"></div>
</form>
</body>
</html>
再新建一个 JayrockHandler.ashx 文件, 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Jayrock.JsonRpc;
using Jayrock.JsonRpc.Web;
using Jayrock.Json.Conversion;
namespace JoyrockWebDemo
{
public class JayrockHandler : JsonRpcHandler
{
[JsonRpcMethod("GetHelloWorld")]
public string GetHelloWorld()
{
return "Hello, World!";
}
[JsonRpcMethod("GetUserList")]
public string GetUserList()
{
//定义实体类列表
List<UserEntity> list = new List<UserEntity>();
//加一些数据
list.Add(new UserEntity() { userID = 1, userName = "kevin1", userSex = "man" });
list.Add(new UserEntity() { userID = 1, userName = "kevin2", userSex = "man" });
list.Add(new UserEntity() { userID = 1, userName = "kevin3", userSex = "man" });
//序列化为json格式字符串
return JsonConvert.ExportToString(list);
}
}
/// <summary>
/// 建一实体类
/// </summary>
public class UserEntity
{
public int userID { set; get; }
public string userName { set; get; }
public string userSex { set; get; }
}
}
这个东西又给我们一个前端javascript调用后端的业务方法提供了简便的思路。不需要再借用JQuery及Newtonsoft.Json.dll等多个三方支持类库框架达到我们需要。是个挺好的东西哦。大家可以不妨一试哦。当然这类库里面还有好多方法功能;有兴趣的大家自己可以进一步研究了。
这里有来自网上关于其简介。大家不妨看看。
Joyrock简介:
Joyrock 是一个基于LGPL协议的开源项目,实现了JSON和JSON-RPC,支持微软ASP.NET框架。它方便我们读取从浏览器流向服务器的JSON对象,也方便在响应流中写入JSON对象。
Jayrock 远程方法要求写在一个ashx中,页面请求这个ashx的时候,在ProcessRequest 中根据Request对象中的参数信息,确定请求的服务器端方法名称和参数,然后进行调用,并返回结果。
官方简介url:http://jayrock.berlios.de/
学习资料链接:J
本文Dome例子下载:http://download.youkuaiyun.com/detail/chz_cslg/4334386
Kevin.Chen
2012年5月24日 于苏州太仓