接着昨天配置好的环境,我开始了简单的尝试。
简单做了个WebPart,其实就是很简单的一个HelloWorld(好像很多大牛写示例也喜欢从Hello World开始,个人认为这个Hello World虽简单,但是她确能给你尝试的成功,往往通过简单Hello World会让你明白很多事情哦)。
首先我从Blank Tmeplate里建了一个Solution,我起名为Jet.SharePoint,保存到我的Samples文件夹下这是我个人的一种开发习惯,习惯把自己写的一些Sample统一管理,同时也方便代码的重用哦。
下面开始正式的WebPart了:
1、在Jet.SharePoint里,添加新项目WebParts,在创建项目时选择项目Template为Class Library;
2、需要把Microsoft.SharePoint和System.Web两个Assambly引用到项目当中,这是因为我在下面创建的类中需要用到;
3、修改我的WebParts项目属性,把Default Namespace 改为Jet.Samples.SP.WebParts,在Signing选项新建加SNK文件并把Sign The Assembly勾上;
4、删除创建项目时自动生成的Class1.cs文件,然后重新添加一个Class,命名为HelloWorld.cs;
5、添加对System.Web、 System.Web.UI、 System.Web.UI.WebControls、
Microsoft.SharePoint.WebPartPages 命名空间的引用;
6、然后添加HelloWorld的类体;这里我们要重写Render和CreateChildControls两个基类方法,这里我创建了一个Literal控件,然后给其Text属性赋Hello World,然后输出到UI上。这里要特别指出一定要给class的添加上public的访问修饰符,在新建class时IDE没有特别指定其访问方式,而按照.net Framework正常的是如果不给class添加访问修饰符,其默认的是internal。
7、修改项目的Assembly.cs,添加[assembly: AllowPartiallyTrustedCallers()]
(详见:如何以便可从 Web页访问具有强名称程序集使用的程序集 AllowPartiallyTrustedCallers 属性)
8、至此我的WebPart HelloWorld完成,剩下的就是build喽。
下面是HelloWorld的详细代码:
using System;2
using System.Collections.Generic;3
using System.Text;4
using System.Web;5
using System.Web.UI;6
using System.Web.UI.WebControls;7
using Microsoft.SharePoint.WebPartPages;8

9
namespace Jet.Samples.SP.WebParts10
{11
class HelloWorld : WebPart12
{13
Literal litHelloWorld = null;14

15
protected override void Render(HtmlTextWriter writer)16
{17
this.litHelloWorld.RenderControl(writer);18

19
base.Render(writer);20
}21

22
protected override void CreateChildControls()23
{24
litHelloWorld = new Literal();25
litHelloWorld.ID = "_litHelloWorld";26
litHelloWorld.Text = "Hello World!";27
this.Controls.Add(litHelloWorld);28

29
base.CreateChildControls();30
}31
}32
}33



浙公网安备 33010602011771号