Advantages and disadvantages of usercontrol in asp.net

后端 未结 3 804
有刺的猬
有刺的猬 2021-01-15 00:06

Can some one please tell me if I should use user controls in my project as much as I can? Ff so why and if not why not?

相关标签:
3条回答
  • 2021-01-15 00:24

    User controls are good for the same reasons that subroutines/functions/methods are good: code (and markup) re-use.

    Like subroutines, controls can be a problem if they do things like modify global state, make lots of DB or other off-box calls that aren't always needed, introduce unavoidable synchronous blocking, etc. They can also add an unnecessary layer of complexity if they are never re-used.

    0 讨论(0)
  • 2021-01-15 00:29

    It's an interesting question; but think of it this way.

    You've just written a table, listing all of your users. You show this on the List Users page of your website.

    On the "Find User" page, you might want to be able to show a list of users. Do you rewrite the same HTML, code, javascript, CSS as before? Or do you reuse the control, this time adding the ability to filter by a user name or other attributes?

    Essentially, user controls are there to package up reusable bits of your website. Rather than repeating the same code everywhere, you can package it up in a user control, and simply add it to any page you want just by adding the appropriate tag.

    Also, you have just made ONE control in your project responsible for dealing with some functionality - all of the logic for it is in one place and separated from other code. This is an important concept too, as it stops all of your code being jumbled together. In the users example, you can interact with a list of users through an interface, rather than mixing it with other code that might do different things. This is called SRP and can be a good thing.

    As a practical example, we have a control that shows a list of our products. We can reuse the same control on the Find screen, the Admin screen, the "Products Like this" screen, and on the "Products you have chosen" screen. This code contains a lot of logic that is all in one place so it can be maintained easily, and it can be reused very simply too.

    User Controls can be a very good thing. So you should use them when you feel like you can package up a group of existing controls, HTML etc. It makes them reusable, and much easier to maintain.

    There is also the concept of custom controls - these are usually reimplementations of existing controls - you might have an ExtendedTextBox, for example, that validates the text as someone types it.

    You can read more about both kinds of controls here

    0 讨论(0)
  • 2021-01-15 00:38

    I would use the controls that the VS IDE Toolbox provides as much as possible. I would only roll my own control if something that the environment supplied, didn't quite do what I wanted it to do.

    0 讨论(0)
提交回复
热议问题