用JS + WCF构建轻量级WebPart

 

先来看下http://www.jscode.cn/jave_page/300804727.htm那方面包车型客车拖放特效(muxrwc兄的创作,博客地址http://blog.csdn.net/muxrwc),那下边已经落到实处得很科学的,布局的保存是用cookie达成的,大家把它修改为运用数据库保存(首要思路就是保存布局时把cookie字符串存到数据库中,加载时从数据Curry取出数据起始化),修改后的言传身教效果地址为http://ext.cneds.net(随时可能会被停掉,呵呵)

(2)新闻表T_News

后记:
实在本文没有啥样出格的技术含量,就是WCF与AJAX的例行应用,我们重回多排练一回,自然也就得心应手了,其实感觉WCF的运用到不算很复杂,JS才是考验web应用真武术的地点(特别是web
2.0的网站).

(2)对应的充实处理的js函数

一致,也是采纳Ajax来加载布局数据

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);

(1)页面上平添多少个按钮
<a id=”Save_CDrag” href=”javascript:void(0);”
style=”display:none”>[封存布局]</a>

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]

忽略:利用CDrag扩充的Ajax功用,向WCF/GetData.svc/SaveLayOutById提交cookie数据写到数据库,再依照重返值给出提醒

自打.net2.0起,ms就出产了webPart成效,用它能够轻放手发出全体web2.0作风的个性化网站功用,比如拖放,定制标题栏等,不过WebPart的统一筹划是属于重量级的,每便拖动都会唤起页面回发,导致数据库读写以及大气的多寡传输(即使在最外层套多少个MajicAjax之类的,也是那样),别的WebPart在非IE标准浏览器上稍稍功力也不能够健康使用。而网上流传的许多JS完毕的特效效能中,已经有不可胜计不易的JS源码,其实大家假若结合.net的效率修改一下,就能实现近似WebPart的功用,而且那种达成完全是轻量级的。

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

(2)新建几个方法:

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

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";
    }

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

 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]

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);
    });

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

3.JS部分

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

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

相关文章