2011-08-01 87 views
3

添加自定义控制我想在我的网站自定义的控制(注意:不是Web应用程序)asp.net网站中

以下是代码

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace AnkitControls 
{ 
    /// <summary> 
    /// Summary description for CustomTreeView 
    /// </summary> 
    public class CustomTreeViewControl : WebControl 
    { 

    } 
} 

的Default.aspx:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" 
    CodeFile="Default.aspx.cs" Inherits="_Default" %> 
    <%@ Register Assembly="AnkitControls" Namespace="AnkitControls" TagPrefix="CustomCtrl" %> 
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> 
</asp:Content> 
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> 
    <h2> 
     Welcome to ASP.NET! 
    </h2> 
    <p> 
     To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>. 
    </p> 
    <p> 
     You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409" 
      title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. 
    </p> 
</asp:Content> 

当我编译的网站,它给我错误的程序集。

错误=“类型或命名空间名称AnkitControls'不存在命名空间存在‘AnkitControls’(是否缺少程序集引用?)”

+0

在您的web.config中引用了'AnkitControls'吗? –

+0

CustomTreeViewControl.cs文件是否放置在本网站的App_Code文件夹中或另一个项目中? –

+0

这是CustomControls文件夹中的网站没有在App_Code文件 – Ankit

回答

1

你检查你的自定义组件的输出二进制文件名AnkitControls .dll? 您是否已将它作为参考添加到您的网站属性中?

+0

这是一个网站,我把代码。它可是没有的DLL添加 – Ankit

+0

好吧,我认为这是在重复使用目的的单独项目 – mmorel

2

正确使用Register标签:

<%@ Register TagPrefix="my" TagName="control" Src="~/Path/To/Your.ascx" %> 

您所指定的语法是当你的控制是另一个程序集中。

+0

然后,它给我的错误缺少装配参考 – Ankit

+0

查看更新的答案。 –

2

您需要将DLL项目添加到您的解决方案并在您的Web项目中引用它,或者如果您在Web解决方案之外开发DLL,只需添加对编译DLL的引用即可。接下来,您需要在您的web.config或页面级别注册该控件。我不建议在网站项目中开发自定义控件。

<%@ Register TagPrefix="ControlVendor" Assembly="ControlVendor" %> 

看看这个网站。 http://weblogs.asp.net/scottgu/archive/2006/11/26/tip-trick-how-to-register-user-controls-and-custom-controls-in-web-config.aspx

如果您在网站项目中创建自定义控件,该类必须驻留在App_Code文件夹中,但注册并不是直截了当,因为Microsoft预先使用ASP命名空间。我这样做很困难,所以我创建了一个DLL项目。