Ajax之所以JS + WCF打造轻量级WebPart

打打.net2.0自,ms就生产了webPart功能,用其可轻松开发有有web2.0风格的个性化网站功能,比如拖放,定制标题栏等,但是WebPart的计划是属重量级的,每次拖动都见面唤起页面回发,导致数据库读写及大气之数额传(即使在极端外层套一个MajicAjax之类的,也是如此),另外WebPart在非IE标准浏览器上有些效果也不能够正常使用。而网上传的无数JS实现的特效功能受到,已经有广大正确的JS源码,其实我们而结合.net的效果修改一下,就能落得近似WebPart的成效,而且这种实现完全是轻量级的。

先期来拘禁下http://www.jscode.cn/jave_page/300804727.htm这地方的拖放特效(muxrwc兄的著作,博客地址http://blog.csdn.net/muxrwc),这地方都落实得深科学的,布局之保留是故cookie实现之,我们管其修改为以数据库保存(主要思路就保存布局时拿cookie字符串存到数据库被,加载时打数据库里取出数据初始化),修改后的言传身教效果地址为http://ext.cneds.net(随时可能会见被停止少,呵呵)

1.数据库结构:
(1)布局表T_LayOut

CREATE TABLE [dbo].[T_LayOut](
 [F_ID] [int] IDENTITY(1,1) NOT NULL,
 [F_LayOut] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT
NULL,
 CONSTRAINT [PK_T_LayOut] PRIMARY KEY CLUSTERED
(
 [F_ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

(2)新闻表T_News

 CREATE TABLE [dbo].[T_News](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [Title] [nvarchar](200) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_T_News] PRIMARY KEY CLUSTERED
(
 [ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

 

2.WCF部分
(1)新建一个启用了Ajax的WCF:MyData.svc
svc文件中,修改为
<%@ ServiceHost Language=”C#” Debug=”true” Service=”GetData”
CodeBehind=”~/App_Code/GetData.cs” Factory=”System.ServiceModel.Activation.WebServiceHostFactory”
%>

web.config中手动修改节点,参考以下:
<behaviors>
   <endpointBehaviors>
    <behavior name=”GetDataAspNetAjaxBehavior”>
     <!–<enableWebScript/>–>                   
    </behavior>
   </endpointBehaviors>
  </behaviors>

(2)新建几独主意:

Code
//取得页面布局数据
[OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetLayOutById?id={id}", Method = "GET")]
    public Stream GetLayOutById(int id)
    {
        //System.Threading.Thread.Sleep(2000);
        string _Result = "";
        using (DBDataContext db = new DBDataContext())
        {
            try
            {
                _Result = db.T_LayOuts.Where(c => c.F_ID == id).Select(c => c.F_LayOut).First();
            }
            catch { }
            finally { db.Connection.Close(); }
        }

        MemoryStream ms = new MemoryStream(); 
        StreamWriter sw = new StreamWriter(ms);
        sw.AutoFlush = true; 
        sw.Write(_Result); 
        ms.Position = 0; 
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; 
        return ms;
    }

//保存布局
    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "SaveLayOutById?id={id}&layout={layout}", Method = "GET")]
    public string SaveLayOutById(int id,string layout)
    {
        string _Result = "false";
        using (DBDataContext db = new DBDataContext())
        {
            try
            {
                var _layout = db.T_LayOuts.Where(c => c.F_ID == id).Single();
                _layout.F_LayOut = layout;
                db.SubmitChanges();
                _Result = "true";
            }
            catch { }
            finally { db.Connection.Close(); }            
        }
        return _Result;
    }


//取得新闻
    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetNews?id={id}&limit={limit}", Method = "GET")]
    public Stream GetNews(int id,int limit)
    {
        string _Result = "";
        using (DBDataContext db = new DBDataContext())
        {
            try
            {
                var query = db.T_News.Select(c => c.Title).Take(limit).ToList();
                for (int i = 0; i < query.Count; i++)
                {
                    _Result += query[i] + "<br/>";
                }
            }
            catch { }
            finally { db.Connection.Close(); }
        }

        MemoryStream ms = new MemoryStream();
        StreamWriter sw = new StreamWriter(ms);
        sw.AutoFlush = true;
        sw.Write(_Result);
        ms.Position = 0;
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
        return ms;
    }


//取得图片地址
    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetPic", Method = "GET")]
    public string GetPic()
    {
        return "http://www.baidu.com/img/baidu_logo.gif";
    }

3.JS部分

(1)页面及平添一个按钮
<a id=”Save_CDrag” href=”javascript:void(0);”
style=”display:none”>[保留布局]</a>

(2)对应之增加处理的js函数

Code
(function(wc) {
                $("DEL_CDrag").onclick = function() {
                    wc.del_cookie();
                    window.location.reload();
                };
                $("ADD_CDrag").onclick = function() {
                    wc.append();
                };
                $("Save_CDrag").onclick = function() {
                    _cookie = wc.get_cookie();
                    _url = "WCF/GetData.svc/SaveLayOutById?id=" + encodeURIComponent(id) + "&layout=" + encodeURIComponent(_cookie) + "&time=";
                    _callBack = function(str) {
                        if (str == "\"true\"") {
                            alert("布局保存成功!");
                            disableSaveButton();
                        }
                        else {
                            alert("布局保存失败!");
                        }
                    };

                    _ajax.initialize(_url);
                    _ajax.send(_url, _callBack);
                }
            })(_wc);

不经意:利用CDrag扩展的Ajax功能,向WCF/GetData.svc/SaveLayOutById提交cookie数据形容及数据库,再依据返回值为有提示

(3)页面初始加载函数修改

Code
Object.addEvent(window, ["onload"], function() {

        $("loading").innerHTML = "布局加载中";

        var _wc = new CDrag, _ajax = CDrag.Ajax.prototype, _cookie = _wc.get_cookie(), _callBack = null, _url = "";

        _url = "WCF/GetData.svc/GetLayOutById?id=" + encodeURIComponent(id) + "&time=";

        //加载完成的回调函数
        _callBack = function(str) {
            _cookie = str;
            json = _cookie ? _wc.parse_json(unescape(_cookie)) : [
                { cols: "m_1", rows: [
                    { id: "m_1_1", window: 1, locks: false },
                    { id: "m_1_2", window: 1, locks: false },
                    { id: "m_1_3", window: 1, locks: false }
                ]
                }, {
                    cols: "m_2", rows: [
                    { id: "m_2_1", window: 1, locks: false },
                    { id: "m_2_2", window: 1, locks: false },
                    { id: "m_2_3", window: 1, locks: false }
                ]
                },
                { cols: "m_3", rows: [
                    { id: "m_3_1", window: 1, locks: false },
                    { id: "m_3_2", window: 1, locks: false },
                    { id: "m_3_3", window: 1, locks: false }
                ]
                }
            ];
            _wc.parse(json);
            (function(wc) {
                $("DEL_CDrag").onclick = function() {
                    wc.del_cookie();
                    window.location.reload();
                };
                $("ADD_CDrag").onclick = function() {
                    wc.append();
                };
                $("Save_CDrag").onclick = function() {
                    _cookie = wc.get_cookie();
                    _url = "WCF/GetData.svc/SaveLayOutById?id=" + encodeURIComponent(id) + "&layout=" + encodeURIComponent(_cookie) + "&time=";
                    _callBack = function(str) {
                        if (str == "\"true\"") {
                            alert("布局保存成功!");
                            disableSaveButton();
                        }
                        else {
                            alert("布局保存失败!");
                        }
                    };

                    _ajax.initialize(_url);
                    _ajax.send(_url, _callBack);
                }
            })(_wc);
            _wc = null;
            $("loading").innerHTML = "";
        }
        _ajax.initialize(_url);
        _ajax.send(_url, _callBack);
    });

同一,也是采用Ajax来加载布局数据

4.源代码下载: http://ext.cneds.net/src/dragdrop.rar (要下载的赶紧,公司的域名现用来用的,随时可能会见停掉)

转载请注明来源菩提树下之杨过http://www.cnblogs.com/yjmyzz/archive/2008/09/20/1294753.html

后记:
实在本文没有什么特别之技术含量,就是WCF与AJAX的正常化应用,大家回到多排几整,自然吧就熟能生巧了,其实感觉WCF的采取及非算是大复杂,JS才是考验web应用真功夫之地方(特别是web
2.0之网站).

相关文章