Why don't my user controls render?

2019-09-19 08:01发布

问题:

I've created a set of user controls in vb.net and in their original project they work fine.

I've since created a user control library dll and I wish to use it in a new project.

I add the reference to the dll fine, specify the tag library in an asp.net page fine and define controls on the page fine.

Everything seems to work except I get no rendered output.

Various properies of the controls and the page_load methods are all called.

Asp.net trace shows the controls in the page hierarchy etc

Just no output where the controls should be - any suggestions?

Update 1

I just compared a trace of the working output compared to the non working.

The working output contains the user controls (and all elements in them) The non working output only lists the user controls - no content

It therefore seems that the content of the controls is missing somehow - as if the markup is not being compiled with the codebehind, only the codebehind seems to be working.

Update 2

The controls are inheriting from UserControl not control.

回答1:

You are correct in your summarization in Update 1- your markup has not been included!

You need to provide a bit of elbow grease if your trying to distribute .ascx controls in a .dll but not too much thankfully.

The two main things you need to do:

  1. Embedded your .ascx controls. The .ascx controls need to be marked as an embedded resource in your .dll (as oppossed to 'content')
  2. Create a VirtualPathProvider. This will allow you to load the ascx files directly from the dll they are embedded in.

Unfortunately explaining step 2 is slightly lengthy, however this excellent article helped me out in doing exactly what you want to do.

The beauty of distributing .ascx controls like this is that you dont have to tear your hair out writing custom controls (rendering anything over than very simple html is a nightmare to make sense of).



回答2:

I assume that you are not confusing between user control (.ascx) and custom controls. For user controls to work, one needs both ascx (mark-up file) along with corresponding code-behind class. User control are typically consists of constituent child controls whose hierarchy is specified within ascx file that provides some UI. In a class library (dll) project, you cannot package ascx files - all you get is the code-behind class. Without ascx, the code-behind class will not have any child controls and hence will render empty. In short, you cannot package user controls (ascx) in a class library - you have to add them into your actual web project.

For shared control, one has to use custom controls. Custom controls are code-only and typically provides render override that emits necessary html (or creates the own child control tree dynamically). These controls can be package as a class library and shared across project. Typically, a custom control will also have other helper classes to provide design time assistance (UI Editors etc).