views:

1123

answers:

4

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.

A: 

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

WebDude
It makes a little sense.
Daud
+1  A: 

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>
sontek
+1  A: 
<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.

Martin
+2  A: 

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)

Matt Briggs