ASP.NET: Mixing server controls with client contro

2019-09-01 07:51发布

问题:

Can anyone help?

I normally use server controls i.e Textbox so i can get access to the server side event.

But what if i don't need access to the server side event and i am going to place some jquery or javascript on the textbox for example.

Can i use a standard HTML (client controls) ?

Is this good practice or not?

Thanks in advance

回答1:

YOu can use simple HTML standard control BUT if you want to access that controls value in ASP.NET then you will have to add runat="server tag" see below

<input type="text" runat="server" id="mytxtbox" name="mytxtbox">

If you really want to use HTML controls you can use them. but it will make your life easy to use standard ASP.NET controls if you are trying to access them on server side.

And if you want to access those controls using javascript as well then you can use something like

var mytxtele = document.getElementById('<%= mytxtbox.ClientID %>')

thats how you can get textbox element and play with it in javascript.

This above code is a basic idea, depends how you want it to work



回答2:

1)If the controls are not going to be accessed in the server side, avoid using server controls.

2)When a server control is used, it goes through the whole life cycle starting from initialization to rendering and finally unloading.

3)It also saves the memory constraint on the view state.



回答3:

Yes you can use standard HTML controls, but asp.net controls are more flexible and you will have the same html output for each control types. If you need to use JQuery and you have problems with controls IDs, see the documentation because you can write something like this (suppose JQuery in asp.net tag):

$('#<%=this.clientId%>').style.display = 'block';

Anyway, I'm sure that there is a method in JQuery to call a single object also when know only a part of his ID name (but I don't remember how.. :))