在sharepoint中应用AJAX技术

AJAX的到来给用户带来更完美的操作体验是不言而喻的!既然有前车之鉴,那我们是不是也把这项技术也应用到sharepoint呢?答案是肯定的,而且实现起来并不难。本章节笔者主要是开发一个Searchwebpart实现局部的无刷新的用户体验.当然你也可以把SriptManager放在指定的masterpage让整个页面都实现无刷新。

前期准备:

1.       下载ASP.NET 2.0 AJAX Extensions 1.0.msi,安装在MOSS所在的服务器环境中安装过程将 ASP.NET AJAX 1.0 程序集 (System.Web.Extensions.dll) 部署到全局程序集缓存 (GAC) 并安装 Microsoft AJAX Library JavaScript 文件

2.       如果您使用的是 .NET Framework 3.5,请将每个 XML 代码示例中的版本号从 Version=1.0.61025.0 更改为 Version=3.5.0.0

3.       应用QuikPart开发webpart并对AJAX了解!

4 .A在母版页板页<header></header>内加入

                <script type='text/javascript'>_spOriginalFormAction = document.forms[0].action;

                _spSuppressFormOnSubmitWrapper=true;</script>

               B.在<WebPartPages:SPWebPartManager id="m" runat="Server" />下面添加实现整页无刷新

               <asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>

<1>首先安装AJAX Extensions 1.o

 <2>.修改自己指定应用程序端口中的配置文件,笔者建议大家最后直接用VS打开,便于发现错误,用记事本太杂乱而且也没错误提示!

这里要注意几点1. <configSections>元素必须紧跟在<configuration>元素下作为其第一子元素,不然运行站点会报错。

                            2. <system.web.extensions></system.web.extensions>必须放在<configuration>的最底端,笔者刚开始放在前端也报错了

                            3.元素里面的type记得和前面的内容空格

    1. <configSections> 元素内添加以下 <sectionGroup> 元素。

      

<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup,System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35">
      
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup,System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35">
         
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection,System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
      
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35">
         
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection,System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" />
         
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection,System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
         
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection,System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
      
</sectionGroup>
      
</sectionGroup>
      
</sectionGroup>

b.在 <system.web> 元素中的 <pages> 元素内添加以下控件声明。

             

  <controls>
          
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        
</controls>

C。在 <assemblies> 元素内添加以下程序集声明

 <add assembly="System.Web.Extensions, Version=1.0.61025.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

D.在 <httpHandlers> 元素内添加以下谓词处理程序。

 <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

 E。在 <httpModules> 元素内添加以下脚本模块处理程序。

 

 <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

F。在 <SharePoint> 元素中的 <SafeControls> 元素内添加以下安全控件项。

 

<SafeControl Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TypeName="*" Safe="True"/>

G。在 <configuration> 元素内添加以下脚本 Web 服务处理程序。


<system.web.extensions>
        
<scripting>
          
<webServices>

                
<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->

                
<!--<authenticationService enabled="true" requireSSL = "true|false"/> -->

                
<!-- Uncomment these lines to enable the profile service.  To allow profile properties to be retrieved and modified in 
                 ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and writeAccessProperties attributes. 
-->
              
<!--<profileService enabled="true" readAccessProperties="propertyname1,propertyname2" writeAccessProperties="propertyname1,propertyname2" /> -->

        
</webServices>

            
<!--<scriptResourceHandler enableCompression="true" enableCaching="true" />-->

        
</scripting>

    
</system.web.extensions>

    
<system.webServer>

        
<validation validateIntegratedModeConfiguration="false"/>

        
<modules>

            
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
       
</modules>

        
<handlers>

            
<remove name="WebServiceHandlerFactory-Integrated" />

            
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
            
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
       
</handlers>
  
</system.webServer>

<3>前期准备都搞定之后,开始步入正题,创建一个web应用程序,笔者取名为AjaxWebpart

添加一个usercontrol命名为AjaxWebpartControl

 1.在页面添加一个ScriptManager(每个页面有且只有一个),一个UpdatePanel ,一个TextBox,Button,GridView,lable.

2.由于笔者做的是利用关键字查询所以记得添加引用:Microsoft.Office.Server.Search, Microsoft.Office.Server. Microsoft.Sharepoint。然后在页面上导入命名空间。

3. 点击项目属性->生成后事件:

   copy "$(TargetPath)" C:"Inetpub"wwwroot"wss"VirtualDirectories"8080"bin

copy "$(ProjectDir)*.ascx" C:"Inetpub"wwwroot"wss"VirtualDirectories"8080"wpresources具体如图:

代码页:这边笔者在代码内容有做相应的注释,相信大家都明白。其中关键一点记得在page_load添加一下我用蓝色标注的代码

using System;

using System.Data;

using System.Configuration;

using System.Collections;

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 Microsoft.Office.Server;

using Microsoft.Office.Server.Search.Query;

using Microsoft.SharePoint;

 

namespace AjaxWebpart

{

    public partial class AjaxWebpartControl : System.Web.UI.UserControl

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (this.Page.Form != null)

            {

                String fixupScript = @" _spBodyOnLoadFunctionNames.push(""_initFormActionAjax"");

                function _initFormActionAjax()

               {

                   if (_spEscapedFormAction == document.forms[0].action)

                      {

                         document.forms[0]._initialAction =

                         document.forms[0].action;

                     }

               }

               var RestoreToOriginalFormActionCore =

               RestoreToOriginalFormAction;

               RestoreToOriginalFormAction = function()

              {

                   if (_spOriginalFormAction != null)

                     {

                        RestoreToOriginalFormActionCore();

                        document.forms[0]._initialAction=document.forms[0].action;

                     }

              }";

                  ScriptManager.RegisterStartupScript(this,typeof(AjaxWebpart.AjaxWebpartControl), "UpdatePanelFixup", fixupScript, true);

            }

        }

 

        protected void Btn_Search_Click(object sender, EventArgs e)

        {

            if (txtQueryText.Text !=string.Empty)

            {

                //执行搜索

                this.ExcutSearch(txtQueryText.Text);

            }

            else

            {

                //提示搜索框不能为空

                this.lblQueryResult.Text = "请输入您要查找的内容!";

            }

        }

 

        //执行关键字搜索

        public void ExcutSearch(string _Qurytext)

        {

            SPSite site = new SPSite("http://mosingserver:8080");//获取应用程序端口对象

            KeywordQuery Keyword = new KeywordQuery(site);

            Keyword.QueryText = _Qurytext;

            Keyword.SelectProperties.Add("Title");

            Keyword.SelectProperties.Add("Path");

            Keyword.SelectProperties.Add("Author");//搜索结果显示的字段

            Keyword.SortList.Add("Title",Microsoft.Office.Server.Search.Query.SortDirection .Descending);//以标题降序

            Keyword.ResultTypes = ResultType.RelevantResults;//返回RelevantResults类型

            ResultTableCollection resultcollection = Keyword.Execute();

            if (resultcollection.Count > 0)

            {

                site.AllowUnsafeUpdates = true;//允许安全模式更改

                ResultTable resulttable = resultcollection[ResultType.RelevantResults];//再次声明返回的类型

                if(resulttable.TotalRows==0)

                {

                    grdResults.Visible = false;

                    lblQueryResult.Text = "您搜索的内容不存在,请改用别的关键字!";

                }

                else

                {

                    lblQueryResult.Text = "";

                    grdResults.Visible = true;

                    ReadResultTable(resulttable);

               

                }

            }

        }

 

        public void ReadResultTable(ResultTable rt)

        {

            DataTable relResultsTbl = new DataTable();

            relResultsTbl.TableName = "Relevant Results";

            DataSet ds = new DataSet("Resualtset");

            ds.Tables.Add(relResultsTbl);

            ds.Load(rt, LoadOption.OverwriteChanges, relResultsTbl);//把结果值填充到DataSet

            DataBindGridView(ds);

       }

        //绑定GridView,显示结果

        public void DataBindGridView(DataSet ds)

        {

            grdResults.AllowPaging = true;

            grdResults.PageSize = 8;

            grdResults.DataSource = ds;//绑定GridView

            grdResults.DataBind();

       

        }

 

        protected void grdResults_PageIndexChanging(object sender, GridViewPageEventArgs e)

        {

            grdResults.PageIndex = e.NewPageIndex;

            grdResults.DataBind();

        }

   }

}

 

项目源码页:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AjaxWebpartControl.ascx.cs" Inherits="AjaxWebpart.AjaxWebpartControl" %>

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

    Namespace="System.Web.UI" TagPrefix="asp" %>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

    <ContentTemplate>

        <asp:TextBox ID="txtQueryText" runat="server" Width="260px"></asp:TextBox>

        <asp:Button ID="Btn_Search" runat="server" OnClick="Btn_Search_Click" Text="搜索" /><br />

        <asp:GridView ID="grdResults" runat="server" CellPadding="4" ForeColor="#333333"

            GridLines="None" Height="217px" Width="598px" AutoGenerateColumns="False" OnPageIndexChanging="grdResults_PageIndexChanging">

            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <RowStyle BackColor="#EFF3FB" Height="10px" />

            <EditRowStyle BackColor="#2461BF" />

            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Height="13px" />

            <AlternatingRowStyle BackColor="White" />

            <Columns>

                <asp:HyperLinkField DataNavigateUrlFields="Path" DataTextField="Title" HeaderText="Title">

                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />

                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />

                </asp:HyperLinkField>

                <asp:BoundField DataField="Author" HeaderText="Author">

                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />

                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />

                </asp:BoundField>

            </Columns>

        </asp:GridView>

&nbsp;<br />

                <asp:Label ID="lblQueryResult" runat="server" ForeColor="Red" Width="129px"></asp:Label>

    </ContentTemplate>

</asp:UpdatePanel>

 

在开发UserControl记得养成好习惯,生成项目之前在文件->高级保存选项->选中UTF-8,避免生成项目后,加载该控件乱码。

生成成功!

 <4>回到站点。笔者创建一个Mysearch页面

添加QuilPart部件然后加载刚才创建的AjaxWebpartControl.ascx确定,进行测试!

一闪而过,瞬间的感觉就是挺完美的!

本次AJAX的应用资料参考来源http://msdn.microsoft.com/zh-cn/library/bb861898.aspx

www.blogs.msdn.com/sharepoint/archive/2007/03/02/integrating-asp-net-ajax-with-sharepoint.aspx

ASP.NET 2.0 AJAX Extensions 1.0.msi下载 http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en

 

posted @ 2009-04-13 01:05  萍水相逢  阅读(848)  评论(4编辑  收藏  举报