Is there a way to redirect or override an existing ASCX? - asp.net

I am working on a ASP.NET site that uses several ascx files scattered throughout the web project, I want to add my ascx files but keep the existing code-behind file. I also want to enable the user to easily switch between the mine and the existing ones. Ideally, I want to enable the user to install the ascx files with minimal hassle without changing any code or going through some complex error-prone process. (The goal is to provide a change of the markup code)
ASP.NET provides ControlAdapters, a mechanism that allows a server control to be customized through adapters that map to a server control. I was wondering if such a mechanism exists for user controls, if not, are there any features or a work-around that provides the same results.
EDIT:
I discovered a "feature" that's not well documented that may allow me to do what I want. It's called tagMapping. It is supposed to work with server controls, but it's failed to work with UserControls.

You can add a panel to where you want to display these user controls. Then, load user controls dynamicly how you wish on backend.
UserControl ctrl = (UserControl)this.LoadControl("/UserControls/"
+ whichone + "/.ascx");
yourpanel.Controls.Add(ctrl);

Related

Dynamic User Controls in asp.net

Hello I am trying to lear how to create Dynamic User Controls in asp.net.
I just know that this type of controls are created or loaded at run time.
Someone knows a good tutorial about this topic?
thanks in advance,
The best thing you can learn about dynamic controls in ASP.Net webforms is how to avoid them. Dynamic controls in asp.net are filled with pitfalls. I almost always recommend one of the following alternatives:
Place a reasonable fixed number of controls on the page, and then only show the ones you need.
Figure out the source for the dynamic controls and abstract it out to a datasource (array, ienumerable, list, etc) that you can bind to a repeater, even if it's just a call to Enumerable.Range().
Build a user control that outputs the html you want, bypassing the entire "controls" metaphor for this content.
If you really must work with dynamic controls, it's important to keep the stateless nature of http in mind, along with the asp.net page life cycle. Each adds it's own wrinkle to making dynamic controls work: the former that you need to create or recreate the controls every time you do a postback, and the latter that you need to do this before hitting the page load event - usually in page init or pre-init.
Typically what people are talking about here is the dynamic instantiation and addition of a control to a placeholder.
For example
Control ControlInstance = LoadControl("MyControl.ascx");
myPlaceholder.Controls.Add(ControlInstance);
The above instantiates MyControl.ascx and places it inside of a placeholder with id of myPlaceholder.
I agree with #Joel by knowing the page lifecycle, the stateless nature in mind etc it is possible to avoid the pitfalls. The main things to watch out for, which I have had to do, are:
Page_Init – initialise the controls that are on the page here as they were the last time you rendered the page. This is important as ViewState runs after Init and requires the same controls initalised the same way as the way they were previously rendered. You can load the control using the code from #Mitchel i.e.
Control ControlInstance = LoadControl("MyControl.ascx");
myPlaceholder.Controls.Add(ControlInstance);
Page_Load – Load the content of the controls in here as you would with any control that isn’t dynamically loaded. If you have kept a reference to them in your page_init they will therefore be available here.
Keeping to this structure I haven’t had too much difficulty as this is appears to be the way that ASP.NET was designed to work, even if all the samples on MSDN don’t do it this way. The biggest thing that you then have to watch is tracking what state the page was in in regard to the controls that you have had rendered.
In my case it was take the section number of the multipage survey and reload the questions from the database, so all I had to do was track the currently rendered section number which wasn’t difficult.
Having said all that if you are using dynamic controls just to show and hide different views of the same screen then I suggest you don’t use them. In this case I would much rather use either user controls (with the inappropriate ones hidden), placeholders to mark areas that aren’t to be rendered yet, or separate pages/views etc. as that way you keep the pages to a single responsibility which makes it easier to debug and/or get useful information from the user about which page they were on.
The Microsoft article is very good, but the best article that I have been read is in the bellow link:
https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx
If you are really interested in ASP.NET Web Forms dynamic controls, I recommend that you study the DotNetNuke CMS Portal. DotNetNuke is one of the best cases using dynamic controls as your core feature to build dynamic portals and pages using ASP.NET Portals. It is free for download in www.dotnetnuke.com.
I hope it helps

why not user control?

why should be used use control template in asp.net? please, someone say me.
Can anyone tell me why I should use a Control Template over a UserControl in ASP.Net?
If you're familiar with MVC, a User Control is like the WebForms equivalent of a partial view.
Update (when I answered, the question asked when to use a User Control...):
A server control is appropriate when you want to bundle assets and functionality for wider distribution than a single project. It is more complex to develop a server control than it is a User Control, but a server-control allows you to completely encapsulate HTML, CSS, JavaScript, images, and server-side logic within a single DLL.
Conversely, a User Control is much easier to develop, but cannot contain assets such as external CSS/JS or images. User Controls are basically just partial bits of an ASPX page.
Unless you know that you need the features of a server control, I would always recommend a User Control for simple de-duplication of content that's repeated in multiple ASPX pages.
A User Control enables you to create your own custom control modules. They're useful because they are reusable, meaning you don't have to duplicate a lot of code. You can embed them in ASP.net pages, and you can define methods and properties for them.

I have to integrate an existing asp.net web app into another page by using jQuery's load() method

I have to integrate an existing, simple asp.net web forms app including postbacks etc. into another external site with a jQuery load() call., an app that was intended to be integrated through an iframe. I doubt that's possible without a rewrite of the app.
The app is a basic questionnaire that leads the user to a product suggestion at the end.
Does anyone have any pointers to how I could solve this? I guess I will probably have to rewrite the app with web services and dynamic calls to RenderUserControls, I will also need access to the page that calls the load() and write additional jQuery methods to handle the user input... I will probably have to remove all of asp.net's postback calls and rewrite the handling of the user input?
First of all you should note that the load() function, like all ajax, can only work on the same domain. So if the 'external site' is on another domain ajax is the wrong choice.
It does sounds like a lot of hard work, depending on the complexity of the page. Postbacks can occur in many places - image clicks, combo selects, etc. Also, there are hidden fields to worry about, like the View State and Event handler - those have the same names on both pages. You'll have an easier time if the external site has no state and postbacks.
If the pages are relatively simple this can probably be done. It's been my experience that forms don't work well in other forms, so you'll have to remove one of them (probably the loaded page's form), or place them one after the other. As you've mentioned, you'll have to rewrite postbacks, you'll want to serialize the data. You may be able to change this string to fit the names on the original page (if you've changed the name of the viewstate, etc, it's easier to change it back on the serialized string than to mess with IDs), post it to the original page, and load again.
Personally, as much as I like jQuery, and as much as this project sounds interesting (and it is), I'd probably go for a server-side solution. It sounds much easier to create a user control (that may use ajax itself), or to the expose the page's functionality using web services or better, generic handlers.

ASP.Net Custom controls vs. user controls: Are these two the same

If they are different, under what circumstances should we decide to use either approach?
Also, what is the advantage of ascx over aspx?
user controls are a form of custom control, that gives you a visual designer. They are ideal for use when you want a reusable control within the same web site. (It is possible to create and package user controls as seperate assemblies but that is beyond the scope of this question and I know has been asked on SO).
A custom control is typically used to refer to a Web Control, or a Composite Control which is specialized form of a web control. These controls have no designer and are usually implemented in seperate projects from your web allowing them to be reused accross many sites.
Now your second question, ASCX and ASPX are two different things. ASCX is the extension for a User Control, where as ASPX is an ASP.Net Page. You cannot use an ASCX by itself it must be placed onto an ASPX or Master page.
One way I like to use user controls is I have for example a very complex page which have 7 tabs, 5 of those have grids, of those grids three of them are identicle. Well what I can do is create a seperate user control for the content of the tabs, this now reduces the code I need down significantly (Since three grids are identicle except for the data).
Further more it allows multiple to work on various parts of the page, and it helps me keep everything straight since I am reducing the complexity of the page. You do not use User Controls instead of Pages, you use them in conjuction with a page.
Edit
You do not use ascx over aspx. You use ascx to complement. For example on my site every page has the same footer, but I don't want every page to derive from a single master page. I can create my footer as an acsx control and put it in each of my master pages.
Another example, I have a form that lets a user enter three different date ranges. (And we have other forms). So I put the logic to enable a calender button, and a text box that when clicked on opens up the calender, in a user control. I can then reuse that user control in all my aspx pages.
Custom controls are control build entirely in code. The pro is that you can put them in libreries, add an icon to the toolbox and other fine control.
User controls are more easy to do, and in general is a way to encapsulate things to simplify other pages or when you need to use the same markup in several pages.
The advantage of controls over regular aspx pages is that you only need to do some part of the markup (not the whole page)
User Controls/Composite controls
User controls that are made up of other ASP.Net or custom controls. They are usually quite straight forward and can be created quite quickly. They Are generally not shared across projects however there are some tricks that can allow you to do this.
Custom controls
Custom controls are controls that you implement the UI by creating everything from the HTML output to design time support. Custom controls take much longer to make. You must use either Web.UI.Control or inherit from a sub control (Textbox for example). Custom controls are compiled to binary format to allow them to be distributed more easily. Since they are compiled they can be referenced from the toolbox in visual studio.
There are 2 main advantages to using a control in an aspx page. Encapsulation of logic and reuseability.

Best way to share ASP.NET .ascx controls across different website applications?

Suppose you have 2 different ASP.NET applications in IIS. Also, you have some ASCX controls that you want to share across these 2 applications.
What's the best way to create a "user control library", so that you can use the same control implementation in the 2 applications, withuot having to duplicate code?
Controls have ASCX with HTML + code behind.
Composite controls will be difficult, because we work with designers who use the HTML syntax in the ASCX files to style the controls.
Tundey, we use SVN here. Do you have an example on how to implement your suggestion? How can SVN share the ASP.NET controls?
Thanks!
Scott Guthrie gives some great advice here on how to set up a User Control Library project, then use pre-build events to copy the user controls into multiple projects. It works really well.
http://webproject.scottgu.com/CSharp/usercontrols/usercontrols.aspx
You would need to create composite controls instead of .ASCX controls if you wanted to be able to use them in separate projects.
In addition to what Tundey said, NTFS Link shell extension is helpful when it comes to sharing a large chunk of content (e.g.: a folder with .ascx/.aspx) between otherwise independent projects. In case of code, i think making another working copy from VCS is preferable.
Have a look at this: http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx?msg=1782921
An alternative is to use your source control tool to "share" the ASCX controls between your webapps. This will allow you to make changes to the controls in either application and have the source control ensure the changes are reflected in the our webapps.
The biggest problem I've noticed with controls in ASP.Net is that you can't easily get designer support for both building the control and using the control in a site once you built it. The only way I've been able to do that is create an .ascx control with no code-behind (ie: all the server-side code is in a script tag in the .ascx file with the runat="server" attribute).
But even then, you still have to copy the .ascx file around, so if you ever need to make a change that means updating the file at every location where you've used it. So yeah, make sure it's in source control.
I managed to do this by sacrificing some of the ease of building the controls in the first place.
You can create a Control Library project that will generate a control library DLL for you. The drawback is that you have to create the controls with code only. In my last project, this was fine. In more complicated controls, this may be a problem.
Here's an example:
<DefaultProperty("Text"), ToolboxData("<{0}:BreadCrumb runat=server />")> _
Public Class BreadCrumb
WebControl
<Bindable(True)> _
Property Text() As String
'...'
End Property
Protected Overrides Sub RenderContents(output as HtmlTextWriter)
output.write(Text)
End Sub
Private Sub Page_Load(...) Handles MyBase.Load
' Setup your breadcrumb and store the HTML output '
' in the Text property '
End Sub
End Class
Anything you put in that Text property will be rendered.
Then, any controls you put in here can function just like any other control you use. Just import it into your Toolbox, make your registration reference, then plop it onto the ASP page.
I use StarTeam here and it allows you to "share" objects (files, change requests, requirements etc) across multiple folders. Not sure if Subversion (SVN) has that feature. If it doesn't, here's another trick you can use: create a junction from the primary location of the controls to a location in the other projects. A junction is just like a Unix symbolic link. You can download the tool for creating junctions in Windows from here
I have a suggestion.WE can use user control across multiples application by creating user control inside website project as normally.Then change the website property Use fixed naming and single page assemblies.Then we can use the user control dll into multiple applications.
I recently did a web application that just referenced the files (about 90 in total) from one web application (aspx, master and ascx) without too much of an issue. That said I was using a heavily modified version of the MVP pattern, a lot of interfaces and conventions to keep the complexity down, the same middle tier and one site was a subset of the other.
Big issues:
Master pages (and in turn designers and html view formatting) don’t work on a referenced file so you lose a lot of functionality. A pre-build step and a lot of svn:ignore entries was my hack around this. It was also a pain to get CruiseControl.NET to get the pre-build task to execute in the right folders.
Shared pages/controls need to be extremely aware of what they touch and reference as to avoid bringing in extra dependencies.
Both sites are locked together for deployment.
I now have to pray that the maintainer reads my pokey little document about the mess I made. It’s so far outside of what I’ve seen in ASP.NET projects.
I was under a massive time pressure to get it to work, it does and now both apps are in production. I wouldn’t recommend it but if you’re interested start at:
Add Existing Item, select some files, click on the Add button’s arrow and say Add as a Link.

Resources