JavaScript is used where one want to do something on the client side purely, or wants to send something to the server in a manner that postback does not handle.
But in Visual Studio 2008 controls ASP.NET C# I have seen that when the page is displayed in the browser the controls, namely GridView, FormView, and LINKBUTTON (!) all show this javascript:thing
when the cursor is hovered on them. Why?
Post back still occurs. Even the linkbutton has this JavaScript thing and whenever you click on it, full post back occurs.
Changing label.text
, etc. too is on the page开发者_如何学运维load event!
- so why the JavaScript? Why not a simple button? Why linkbutton?
In this case JavaScript calls could be used to send additional data to the server, e.g. save some client data for the grid (like the width of resized columns or something like that). Server-side frameworks use this approach to allow server-side guys to generate all the client-side code. It's a kind of quick'n'dirty solutions (comparing with well-organized unobtrusive JavaScript).
ASP.NET is stateless. That is, every time a page is requested, the server actually constructs the entire page and its controls & state and then responds to the request. It then renders the appropriate HTML markup as response to the request.
For any control, if there is the autopostback property set to true then a page is postback to the server if the control causes a postback (like clicking on a link button).
How does ASP.NET post back the page ? It does it using a javascript function called _doPostBack(). The function is -
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
This function is used to submit the form back to the server. _doPostBack accepts arguments - event target and event arguments by using hidden variables __EVENTTARGET and __EVENTARGUMENT. This tells the server which control caused the postback and also passes appropriate arguments to the server.
if you have this code in your aspx page -
<asp:LinkButton ID="lnkButton" runat="server">LinkButton</asp:LinkButton>
The corresponding generated markup will be -
<a id="LinkButton1" href="javascript:__doPostBack('lnkButton','')">LinkButton</a>
So, say you click on a link button, the page is postback by the __doPostBack() function. Then, the page is recreated at server with the respective control state on the page. To get the state of each control on the page mechanisms like viewstate are used. Once the page is loaded, the server computes and renders the response markup.
精彩评论