R – ASP .NET: Dynamic load controls vs Visible = true

asp.netuser-controls

Which one is recommended ? Let me explain what I want to achieve !
I have one pages used by many users, every user has a different Role like admin, operator, normal user.
When a client open that page I want to display a set of controls (buttons) which depends on their Role.
admin is allowed to do x and y, but a normal user is not allowed to do these actions.

In order to achieve what I want to do, which approach is the best one ?
Should I define all controls in HTML then toggle Visible property, or dynamically load needed controls ?


For Visible = false I'm worried about server processing time. Even if HTML markup is not sent to the client for a Visible = false control, I know that the control is still loaded by ASP .NET and maybe even processed, but his HTML result is not written to the output stream.

For dynamically loaded control, one inconvenient is that they need to be reinitialized on Postback, also there are some problems with events and postback.

Best Answer

I wouldn't do it dynamically as the gain is not worth the complexity or perceived savings. Also if you set visible = false, keep in mind that the viewstate is still enabled for your controls. If you are worried about the back and forth data and dealing with a larger viewstate, make sure you disable the viewstate for all the controls or for a parent panel that contains them. You will have the same inconvenience for maintaining their state on postback as doing it dynamically though.

Also, doing it non-dynamically is much easier to maintain to the next guy working with the code. The layout is obvious and easier to visualize than trying to figure out what code when is putting what where.

Creating controls dynamically really doesn't gain you much at all except for the exclusion of viewstate and maybe negligable processing server side. I think you would find it difficult to even measure much of a noticable difference, even under load between, a non-viewstate control and the overhead of dynamically having to add them as needed.

Lastly, it's easier to not do it dynamically so why not take the easiest route first and see if it is a problem. If it does become an issue then refine it where necessary.

Related Topic