In ASP.net is it better to use Server Controls within the ASPX page or create them dynamically in the code behind? - asp.net

I generally prefer to add controls dynamically, like table and generic html controls, to the ASPX page, rather than add them in the ASPX page and set the properties dynamically.
Which approach is considered "better practice"?
Also is using generic html controls dynamically a better practice than outputting formatted html strings to an asp:literal?

Keep them in the .aspx
Adding them dynamically leads to view state issues and they must be added in each post pack. I ran into this when building a user generated forms app. I Broke down and used the controls visibility property as a work around. That said if your eliminating view state and post back from your app these may not be issues for you.
https://web.archive.org/web/20211031102347/https://aspnet.4guysfromrolla.com/articles/092904-1.aspx

Since in both approaches you end up with a set of code that adds controls and assigns values to their properties then the best practice is the approach that is the most readable.
Due to complex decision logic it may be better to do it all yourself on the hand for fairly static control layout where only the properties need modifying placing the control in the ASPX would be more straight-forward.

Related

How to make ASP.NET server controls get the shortest IDs?

I am using ASP.NET 4.0 WebForms. I am also using master pages which inherit from other master pages. I have controls inside panels. Basically there are multilevel containers. This is causing elements to have HUGE ID's. I am seeing ID's about 300 bytes long!
When there are hundreds of elements in a page, these ID's increase the page's size dramatically. I have a GridView with binding controls.
What is the best way to have each server control have the shortest ID possible? Is there a way to have each element not be dependent on its container (other than ClientIDMode="static") ID even if but still be unique in the page? Last, does ASP.NET MVC alleviate this issue?
I would suggest changing the ClientIdMode to either Predictable or Static in order to see if that produces shorter ID's.
Further to that this CodeProject article appears to achieve what you need.
MVC absolutely alleviate this issue because there is no server side rendering of html code in the same manner. All of your html is directly in your views so you have full control over every item. You also run the risk (in the case of a page that has hundreds of inputs) of colliding inputs.
One way you can help shorten all the html produced in WebForms is to remove anything that is not absolutely necessary to be a webusercontrol. For instance, most labels are static. They can replaced normally with standard text or items that don't include the runat="server" attribute. This will prevent ids from being generated in the first place. Another way to reduce the amount of junk that gets generated is to remove as many controls as you can from the ViewState. This will prevent them from loading their state data and keep the ViewState shorter.
ClientIDMode is an inheritable property so you can set it in the web.config (global), web.config (local) or page level. You could also use it individually. Your question specifically eliminates this, but it would probably be the best option with the most flexibility without rewriting what you already have. If rewriting is not an issue, I'd recommend using MVC.
I think ClientIDMode=static is in one of the way. YOu can set this in your web.conf also. And in Asp.Net mvc, you have the full conrol over html (especially in Razor). There is no such thinks like webforms. You have control over assigning ids to html tags. Infact Asp.Net mvc is answer to all other frameworks.
Last, does ASP.NET MVC alleviate this issue?
Yes.
There is no ViewState in MVC and you are not running any controls on the server.
You are not using any server controls which generate tons of hard to read HTML.
You have complete control over ClientID's in MVC.
Click
The above markup will always have the id of myID unless I change it myself.

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

Dynamically creating many instances of ASP.NET usercontrols: How do I create it, and where will my conflicts be?

I haven't seen this implemented before in ASP.NET, but am thinking about a UI that would look and act like this:
Conceptual Overview
A TabControl is loaded and the first tab contains a grid
When a row is double-clicked, a new tab is created with the record detail
The content of the tab/record detail is created by a usercontrol
Many tabs could be created, and therefore many instances of the usercontrol will be created
I know ASP.NET will rename my (runat="server") ID's for me, and that I can use jQuery or ASP.NET server-side code to work with the ID's... My concerns are:
How can I ask ASP.NET to generate a unique ID for each Nth instance of my usercontrol (to be rendered in a placeholder)
How do I actually create that extra instance of the control?
What else do I need to keep in mind?
Since I don't want postbacks I'm considering basing my implementation off of ComponentArt's Callback Control, and using ASP.net usercontrols to achieve this effect. This will allow me to do most things that require a postback, but won't refresh all the elements on a page... just the section that contains the user control. That being said, I'm not tied to a particular implementation.
You should look into the Page.LoadControl method. It works nicely and as far as I remember you put placeholders on your page and load the controls into the PlaceHolders, that's how you control the ids.
One thing that doesn't work out so well with this approach is when your control raises events that your Page object has to handle. If your control is selfcontained however you shouldn't have a problem.
This might help you get started:
http://www.codeproject.com/KB/aspnet/LoadingUSerControl.aspx

How to get a composite-control's child controls at design-time

I am designing an ASP.NET v3.5 custom control based on CompositeControl.
However, I do NOT want to create my child controls via code, but rather as
embedded HTML tag elements within the CompositeControl in the ASPX page, such as:
<cc:MyCompositeControl ID="MyControl">
<asp:Label>Cat</asp:Label>
<asp:Label>Cat</asp:Label>
</cc:MyCompositeControl>
At run time, MyControl.Controls contains the two labels as expected.
At design time, MyControl.Controls is empty.
I need this information at design time for various reasons.
What am I doing wrong?
You might consider taking a look at the System.Web.UI.WebControls.Panel control in the System.Web DLL using Reflector. That will help you get some idea of what properties and what attribute decorations are necessary to provide the design-time support you need.

Register Startup Script Control

I am looking to make a web control where I can register client startup scripts inline with my aspx because I hate registering in the codebehind!
An example of what I have so far:
<Ben:StartupScript runat="server">
var form = document.getElementById("<% =form1.ClientID %>");
</Ben:StartupScript>
Currently, I am overriding the OnPreRender method of the control, rendering the contents of the control to a string and then manually registering that string as a startup script using ClientScript.RegisterStartupScript on the Page. I also override the Render method in order not to render the control. I should also note that I have the ParseChildren attribute set to false and the PersistChildren attribute set to true.
All seems to be working well, but my control allows other web controls inside it (such as Button). Apart from being unintuitive, this can result in runtime errors. I would love to be able to clear the controls but this is impossible given the <% ... %> code block.
So, is it possible to prevent developers from embedding child controls whilst still allowing code blocks?
Also, is this idea any good or is it fundamentally flawed? Lol.
Thanks a bunch,
Ben
it sounds like a good idea, but if you spend too much time fighting the inherited/default behaviors then it may be more trouble than it's worth
if this is a one-shot issue, a cheap-hack solution is to just directly embed your scripts in the header of a master page ;-)
on the other hand, allowing developers to embed their own scripts as children of your web control might be useful
If you are using master pages, add another control in your section. That way you can easily add css/js to your headers in your child pages.
ClientScript.RegisterScript is mostly for user/server controls,

Resources