检查用户名是否可用或已获取

时间:2022-05-23 09:34:46

I have a simple application in ASP.NET C# and using MS SQL Server 2008. I need to register all visitor users to my site. For that users will have to fill a form. The problem is that as the user enters the Desired Username field, I should be able to check in background whether another user has already taken that username. I will have to fire an sql select query to check for the availability.

我在ASP.NET C#中有一个简单的应用程序并使用MS SQL Server 2008.我需要将所有访问者用户注册到我的站点。为此,用户必须填写表格。问题是,当用户输入Desired Username字段时,我应该能够在后台检查另一个用户是否已经使用了该用户名。我将不得不触发一个sql select查询来检查可用性。

Currently I am using the TextBoxName_TextChanged method but it does not work in realtime. It works only on a postback. The code is that follows:

目前我正在使用TextBoxName_TextChanged方法,但它不能实时工作。它仅适用于回发。代码如下:

protected void TextBox3_TextChanged(object sender, EventArgs e)
        {
            if (TextBox3.Text.Length == 0)
            {
                availability.Text = "";
                return;
            }

            SqlDataAdapter adp = new SqlDataAdapter("select username from users where username='" + TextBox3.Text + "'", con);
            DataSet ds = new DataSet();
            adp.Fill(ds, "users");
            if (ds.Tables["users"].Rows.Count > 0)
            {
                availability.ForeColor = System.Drawing.Color.Red;
                availability.Text = "Not Available";
            }
            else
            {
                availability.ForeColor = System.Drawing.Color.White;
                availability.Text = "Available";
            }

        }

Please suggest me something as all I searched on web was about PHP, Not ASP.NET

请给我一些建议,因为我在网上搜索的所有内容都是关于PHP,而不是ASP.NET

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
</asp:UpdatePanel>
    <table cellpadding="5" class="style1"> 
        <tr>
            <td class="style3">
                <asp:Label ID="Label3" runat="server" Text="Username" ForeColor="White"></asp:Label>&nbsp;&nbsp; </td>
            <td style="border:0px none #FF0000;">
                <asp:TextBox ID="TextBox3" runat="server" Width="175px" 
                    CssClass="input-control" ForeColor="Black" ontextchanged="TextBox3_TextChanged" AutoPostBack="true"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="style3"></td>
            <td style="border:0px none #FF0000;"> 

                <asp:Label ID="availability" runat="server" Width="175px" CssClass="text" Text="availability"></asp:Label></td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label4" runat="server" Text="Password" ForeColor="White"></asp:Label>&nbsp;&nbsp;&nbsp; </td>
            <td style="border:0px none #FF0000;">
                <asp:TextBox ID="TextBox4" runat="server" Width="175px" TextMode="Password" CssClass="input-control" ForeColor="Black"></asp:TextBox></td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label5" runat="server" Text="Email" ForeColor="White"></asp:Label>&nbsp;&nbsp;&nbsp; </td>
            <td style="border:0px none #FF0000;">
                <asp:TextBox ID="TextBox5" runat="server" Width="175px" CssClass="input-control" ForeColor="Black"></asp:TextBox></td>
        </tr>

        <tr>

            <td class="style3">

            <td style="width:30%; text-align: right; padding: 10px; border:none;">
                <div class="button-set" data-role="button-set">
                    <asp:Button ID="Button2" runat="server" class="active bg-color-red" Text="Sign Up" />
                </div>
        </tr>
        </table></asp:UpdatePanel>

Update:

更新:

Following Everybody's comments and answers I have achieved this much with a little problem shown in this screenshot: 检查用户名是否可用或已获取 Don't know why there are another label with status and the availability_status stays as it is. Please help.

关注每个人的评论和答案我已经通过此屏幕截图中显示的一个小问题实现了这一点:不知道为什么还有另一个带状态的标签,且availability_status保持不变。请帮忙。

5 个解决方案

#1


2  

I believe that you're update panel is not well formatted. You need to put "availability" label into update panel, then set a trigger for the username text box and then set the event name. something like :

我相信你的更新面板格式不正确。您需要将“可用性”标签放入更新面板,然后为用户名文本框设置触发器,然后设置事件名称。就像是 :

 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
    <asp:Label ID="availability" AppendDataBoundItems="true" runat="server" >                                         
    </asp:Label>
  </ContentTemplate>
  <Triggers>
   <asp:AsyncPostBackTrigger ControlID="TextBox3" EventName="TextChanged" />
    </Triggers>
 </asp:UpdatePanel>

you also nee to set AutoPostBack="True" in your text box. I think it shall work.

你还需要在文本框中设置AutoPostBack =“True”。我认为它会起作用。

#2


1  

Does the textbox have AutoPostBack="true" ? You will certainly need to add an UpdatePanel aroud your textbox in order to prevent the full page load.

文本框是否有AutoPostBack =“true”?您肯定需要在文本框中添加UpdatePanel以防止整页加载。

#3


1  

You need to fire off your request via AJAX. Hook up to the 'changed' event of the text box client side and trigger it from there - best option would be to use jQuery e.g.

您需要通过AJAX发出请求。连接到文本框客户端的“已更改”事件并从那里触发它 - 最好的选择是使用jQuery,例如

<script text="text/javascript">

$(document).ready(function() {
    var searchTimer;
    ...
    $('TextBox3').change(function() {
        var searchTerm = $(this).val();
        clearTimer(searchTimer);
        searchTimer = setTimeout(1000, function() {
            $.get('findUsers', { userName: searchTerm }, function(response) {
                // process successful response
            }).error(function(error) {
                // process error response
            });
        });
    });
});
<script>

<table>
    ...
    <input type="text" id="TextBox3" />
</table>

The above would fire a request to an API call "findUsers" 1 second after every text change. This is to avoid sending unnecessary requests when the user is typing as you only want to send the request when the user has finished.

以上内容将在每次文本更改后1秒钟向API调用“findUsers”发出请求。这是为了避免在用户键入时发送不必要的请求,因为您只想在用户完成时发送请求。

#4


0  

Finally, I got it working, Thanks to all those who took interest and tried. The solution is to make PostBack on every OnkeyUp event, and this can be done using JS.

最后,我得到了它的工作,感谢所有兴趣和尝试的人。解决方案是在每个OnkeyUp事件上创建PostBack,这可以使用JS完成。

The markup is

标记是

<asp:TextBox ID="TextBox3" runat="server" Width="175px" 
                    CssClass="input-control" ForeColor="Black" onkeyup="RefreshUpdatePanel();" ontextchanged="TextBox3_TextChanged" AutoPostBack="false"></asp:TextBox>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate><asp:Label ID="availability" runat="server" Width="175px" CssClass="text" Text="availability_label"></asp:Label>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="TextBox3" EventName="TextChanged" />
                    </Triggers>

The Javascript is:

Javascript是:

<script type="text/javascript">
      function RefreshUpdatePanel() {
          __doPostBack('<%= TextBox3.ClientID %>', '');
      };
</script>

And the code for checking if the username exists or not is written inside the

用于检查用户名是否存在的代码写在

TextBox3_TextChanged() Method. It worked.

TextBox3_TextChanged()方法。有效。

#5


-2  

I recently built this function you can try it out by yourself.

我最近建立了这个功能你可以自己试试。

public bool IsExist(string name, string pass)  /// in your case you only need to save the textbox on a string variable
    {
        string sql = "select * from Users where UName='" + name + "' and Pass='" + pass + "'"; ; 
        DataSet ds = General.GetData(sql); // General class has function called GetData which obviouslly gets the data of the required SQL information.
        if (ds.Tables[0].Rows.Count > 0)
            return true;
        return false;
    }

#1


2  

I believe that you're update panel is not well formatted. You need to put "availability" label into update panel, then set a trigger for the username text box and then set the event name. something like :

我相信你的更新面板格式不正确。您需要将“可用性”标签放入更新面板,然后为用户名文本框设置触发器,然后设置事件名称。就像是 :

 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
    <asp:Label ID="availability" AppendDataBoundItems="true" runat="server" >                                         
    </asp:Label>
  </ContentTemplate>
  <Triggers>
   <asp:AsyncPostBackTrigger ControlID="TextBox3" EventName="TextChanged" />
    </Triggers>
 </asp:UpdatePanel>

you also nee to set AutoPostBack="True" in your text box. I think it shall work.

你还需要在文本框中设置AutoPostBack =“True”。我认为它会起作用。

#2


1  

Does the textbox have AutoPostBack="true" ? You will certainly need to add an UpdatePanel aroud your textbox in order to prevent the full page load.

文本框是否有AutoPostBack =“true”?您肯定需要在文本框中添加UpdatePanel以防止整页加载。

#3


1  

You need to fire off your request via AJAX. Hook up to the 'changed' event of the text box client side and trigger it from there - best option would be to use jQuery e.g.

您需要通过AJAX发出请求。连接到文本框客户端的“已更改”事件并从那里触发它 - 最好的选择是使用jQuery,例如

<script text="text/javascript">

$(document).ready(function() {
    var searchTimer;
    ...
    $('TextBox3').change(function() {
        var searchTerm = $(this).val();
        clearTimer(searchTimer);
        searchTimer = setTimeout(1000, function() {
            $.get('findUsers', { userName: searchTerm }, function(response) {
                // process successful response
            }).error(function(error) {
                // process error response
            });
        });
    });
});
<script>

<table>
    ...
    <input type="text" id="TextBox3" />
</table>

The above would fire a request to an API call "findUsers" 1 second after every text change. This is to avoid sending unnecessary requests when the user is typing as you only want to send the request when the user has finished.

以上内容将在每次文本更改后1秒钟向API调用“findUsers”发出请求。这是为了避免在用户键入时发送不必要的请求,因为您只想在用户完成时发送请求。

#4


0  

Finally, I got it working, Thanks to all those who took interest and tried. The solution is to make PostBack on every OnkeyUp event, and this can be done using JS.

最后,我得到了它的工作,感谢所有兴趣和尝试的人。解决方案是在每个OnkeyUp事件上创建PostBack,这可以使用JS完成。

The markup is

标记是

<asp:TextBox ID="TextBox3" runat="server" Width="175px" 
                    CssClass="input-control" ForeColor="Black" onkeyup="RefreshUpdatePanel();" ontextchanged="TextBox3_TextChanged" AutoPostBack="false"></asp:TextBox>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <ContentTemplate><asp:Label ID="availability" runat="server" Width="175px" CssClass="text" Text="availability_label"></asp:Label>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="TextBox3" EventName="TextChanged" />
                    </Triggers>

The Javascript is:

Javascript是:

<script type="text/javascript">
      function RefreshUpdatePanel() {
          __doPostBack('<%= TextBox3.ClientID %>', '');
      };
</script>

And the code for checking if the username exists or not is written inside the

用于检查用户名是否存在的代码写在

TextBox3_TextChanged() Method. It worked.

TextBox3_TextChanged()方法。有效。

#5


-2  

I recently built this function you can try it out by yourself.

我最近建立了这个功能你可以自己试试。

public bool IsExist(string name, string pass)  /// in your case you only need to save the textbox on a string variable
    {
        string sql = "select * from Users where UName='" + name + "' and Pass='" + pass + "'"; ; 
        DataSet ds = General.GetData(sql); // General class has function called GetData which obviouslly gets the data of the required SQL information.
        if (ds.Tables[0].Rows.Count > 0)
            return true;
        return false;
    }