April 18, 2011

Causing a Specific Control to Postback

I was recently debugging an issue with a form where the user wanted the "enter" button when pressed in a textbox to trigger a specific ASP.NET button to postback to the server.  I have done similar things in the past with a method that changes for the pressing of Character 13 which is the enter key, then finding the button by id and then continuing on.  Well recently I found out that depending on the structure you can still get some "interesting" results.  So I went looking for a different method, and came up with the following.

<script type="text/javascript">
    function checkEnterSearch(e) {
        var characterCode
        e = event;
        characterCode = e.keyCode;
        if (characterCode == 13) { 
            //Action Goes Here
            <%= Page.ClientScript.GetPostBackEventReference(YourControl, "") %>
            return false;
        else {
            return true;

With this script block in your code you can simply make two modifications. Replace the "YourControl" piece with the server side name of your target control, and then add the following attribute definition to all textboxes that you want to have this behavior.

onkeypress="return checkEnterSearch(event);"

This route uses the server side operation "GetPostBackEventReference" which returns essentially a fully executable line of JavaScript that will trigger a postback with the defined target control.

I hope this helps, feel free to share comments/questions below.

tags: ASP.NET, .NET 4.0, Quick Tips
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.