How do I chain my own JavaScript into the client side without losing PostBack functionality

混江龙づ霸主 提交于 2019-12-10 11:57:06

问题


So I was reading these Asp.Net interview questions at Scott Hanselman's blog and I came across this question. Can anyone shed some light of what he's talking about.


回答1:


<asp:LinkButton ID="lbEdit" CssClass="button" 
            OnClientClick="javascript:alert('do something')" 
            onclick="OnEdit"  runat="server">Edit</asp:LinkButton>

The OnClientClick attribute means you can add some javascript without losing PostBack functionality would be my answer in the interview.




回答2:


Explain how PostBacks work

Postbacks are an abstraction on top of web protocols which emulate stateful behavior over a stateless protocol.

, on both the client-side

On the client side, postbacks are achieved by javascript calls and hidden fields which store the state of all controls on the page.

and server-side.

The server side goes through a life cycle of events, part of that life cycle is the hydration of the viewstate to maintain the state of all the controls on the page, and the raising of events based on the paramaters that were passed into the __doPostBack call on the client side

How do I chain my own JavaScript into the client side without losing PostBack functionality?

Depends on what is required. The easiest way that works 99% of the time is to use asp:hiddenfield to communicate between client and server side. For edge cases, you want to get into Exenders and manipulating viewstate/controlstate/clientstate in javascript through the MS ajax APIs. This is pretty painful with a huge learning curve and a lot of gotchas, generally using hidden fields and manually calling __doPostBack is enough


That is how I would answer that bullet point. For more information on __doPostBack, a quick google will give you plenty of results (for the lazy, this is the first hit http://aspalliance.com/895)




回答3:


Do you mean something like this:

in your code behind:

protected string GetPostBack()
{
    return ClientScript.GetPostBackEventReference(this, null);
}

and in your aspx:

<a href="javascript:<%=GetPostBack() %>">Click here to postback</a>



回答4:


I think what he's asking here is how you wire up javascript functions to work hand in hand with your ASP.NET post back functionality.

i.e. How can I trigger a control's event using my own Javascript.

The ASP.NET class library contains a ClientScript class - Found in the System.Web.UI.Page class - which enables you to programmatically add Javascript to your ASP.NET page.

This contains a method called 'GetPostBackEventReference' which will genereate the __doPostBack script ASP.NET utilises to trigger events wired up to your web controls.

Hope that makes sense



来源:https://stackoverflow.com/questions/99917/how-do-i-chain-my-own-javascript-into-the-client-side-without-losing-postback-fu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!