ASP.NET 自定义控件
如何创建自定义控件(不是 ASCX 控件),更重要的是,如何在项目中使用它? 我不想为它创建一个单独的项目或将其编译为 DLL
How do you create a custom control (not an ASCX control) and, more importantly, use it in your project? I'd prefer not to create a separate project for it or compile it as a DLL
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
服务器控件应编译成 DLL。 没有理由害怕在项目中添加额外的程序集,它有助于创建良好的项目组织。
ASP.NET 服务器控件实际上是程序集中的自定义类。 它们没有关联的“ascx”标记文件。
要使用 ASP.NET 服务器控件,您需要告诉 ASP.NET 在哪里查找其类。
首先,创建一个类库项目并将其添加到您的解决方案中,我将其命名为“CustomControls.dll”。
到达那里后,添加一个简单的类作为您的 Web 控件:
构建您的项目,并将其添加为对您的主 Web 项目的引用。
现在,在要使用此控件的 ASPX 页面中,您需要注册它,因此将其添加为 aspx 中页面指令之后的第一行:
现在,您应该有一个名为的控件; 可供您使用。 可能需要一分钟才能显示在智能感知中。
Server controls should be compiled into a DLL. There should be no reason to be afraid of having an additional assembly in your project, and it helps create good project organization.
ASP.NET Server controls are actually custom classes in an assembly. They do not have an "ascx" markup file associated to them.
To use a ASP.NET Server Control, you need to tell ASP.NET where to look for its class.
First, create a Class Library project and add it to your solution, I'll call mine "CustomControls.dll".
Once there, add a simple class to be your webcontrol:
Build your project, and add it as a reference to your main web project.
Now, in the ASPX page that you want to use this control, you need to register it, so add this as the first line in the aspx AFTER the Page Directive:
Now, you should have a control named <Example:Hello> available to you. It might take it a minute to show up in intellisense.
创建控件的类并构建解决方案。 如果一切顺利,该控件现在应该可以在工具箱中使用。
有时VS不会更新工具箱。 如果发生这种情况,请将 Register 指令添加到页面:
然后只需使用页面上的控件:
Create the class for the control and build the solution. If everything goes well the control should now be available on the toolbox.
Sometimes the VS doesn't update the toolbox. If that happens add the Register directive to the page:
then just use the control on the page:
如果你不需要*.ascx文件,你不需要一个单独的项目,你不需要*.dll文件,你认为还剩下什么? 代码必须存在于某个地方。
If you don't want a *.ascx file, you don't want a separate project, and you don't want a *.dll file, what do you think is left? The code has to live somewhere.
您提到您想避免创建单独的项目。 正如其他回复所表明的那样,更常见的是简单地创建一个新项目来存储自定义控件并引用它。 但是,可以使用常规语法注册在同一项目中定义的控件:
其中“程序集”是控件和页面所在的程序集。 如果您使用的是 Web 应用程序项目而不是网站,那么这会更容易。
You mentioned that you wanted to avoid creating a separate project. As the other responses have indicated, it is far more common to simply create a new project to store your custom controls and reference it. It is possible, however, to register a control defined in the same project, using the regular syntax:
Where the "Assembly" is the assembly where both the control and the page is located. This works much easier if you are using a Web Application Project, rather than a Web Site.