用户控件中回车提交问题的解决

今天工作中碰到一个问题,我使用用户控件制作一个搜索框,上面带有一个下接列表及一个文本框
当我把用户控件拖到WebForm上面的时侯,在文本框上随便输入一些文件,直接回车,发现页面是PostBack了,可是并没有引发SearchButton的处理事件。

ascx的源码如下
<DIV align="center">
<asp:dropdownlist id="ddlType" runat="server"></asp:dropdownlist>
<asp:TextBox id="tbxKey" runat="server" Width="105px"></asp:TextBox>&nbsp;
<asp:imagebutton id="imgbtnSearch" runat="server" CausesValidation="False" ImageUrl="~/images/search.gif"></asp:imagebutton>
</DIV>

asp.net是通过ViewState中的数据来判断是哪个Control引发事件,再确定调用的处理方法。以上的问题应该是回车时,页面ViewState里没有正确的指示引发事件的控件引起的。
还有一个问题,就是一个web form页面,如果有多个文本框,多个button,比如,我们一个主页上会有搜索框及搜索button,会员登录框及登录button,最好的实现是用户在搜索框上回车时,提交的是搜索,在会员用户名或密码框上回车时是登录事件。
地球人都知道,用户控件拖到web from上后,用户控件上的控件名称都会发生变化,且一个web from又只能有一个runat server 的Form。这时,经过一番修改后,把用户控件的代码改成如下:

修改后的ascx代码:

<%@ Control Language="c#" AutoEventWireup="false" Codebehind="Search.ascx.cs" Inherits="Dots.CMS.Web.module.Search" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<DIV align="center" onkeypress="javascript:SubmitSearch()"><asp:dropdownlist id="ddlType" runat="server"></asp:dropdownlist>
<asp:TextBox id="tbxKey" runat="server" Width="105px"></asp:TextBox>&nbsp;
<asp:imagebutton id="imgbtnSearch" runat="server" CausesValidation="False" ImageUrl="~/images/search.gif"></asp:imagebutton></DIV>
<script language="javascript">
    
function SubmitSearch(){
        
if(window.event.keyCode==13){
            
var eleId = event.srcElement.id;
            
if(eleId.indexOf('tbxKey') > 0){
                
var    btnId = eleId.substring(0, eleId.indexOf('tbxKey')) + 'imgbtnSearch';
                document.getElementById(btnId).click();
            }

        }

    }

</script>
<input style="display:none" />

此时,不管这个搜索框的用户控件拉到哪里,只要在文本框上直接回车,就能提交这个搜索框了。

但要注意就是没有<input style="display:none" />这部分就会不成功,不知道为什么,呵呵。(网上搜了一下,也有朋友提出这个问题,但没有答案),我的做法有什么不对的地方,也请指正,谢谢!

posted @ 2006-12-29 21:57  Allen Zhang  阅读(3837)  评论(14编辑  收藏  举报