简体   繁体   English

AutoPostBack和RequiredFieldValidator行为

[英]AutoPostBack and RequiredFieldValidator behaviour

I have a username text box with AutoPostBack property and RequiredFieldValidator .The problem is when I type something in the text box then come out of it thus triggering AutoPostBack now if I come back to the text box and delete what I have typed and then come out of textbox the form displays the message "Username is required" but its just flashes for a second and then the page refreshes . 我有一个带有AutoPostBack属性和RequiredFieldValidator的用户名文本框。问题是当我在文本框中键入内容然后从中出来时,如果我回到文本框并删除键入的内容然后出来,则立即触发AutoPostBack文本框的表单显示消息“需要用户名”,但它仅闪烁一秒钟,然后页面刷新。
I don't understand this behaviour . 我不明白这种行为。 Can I somehow change the form so that either the "Username is required" message stays or it doesnt flash at all. 我可以以某种方式更改表格,以便保留“ Username is required”消息或根本不闪烁。 And if I come out of the text box without typing nothing happens (not even AutoPostBack I think) 而且,如果我没有输入任何文字就从文本框中出来(我认为甚至连AutoPostBack都不会发生)
The other problem is same but I think my doubts are a bit different: 另一个问题是相同的,但我认为我的疑问有所不同:
Why is RequiredFieldValidator not fired if the text box is empty and I press tab or what actually triggers RequiredFieldValidator 为什么RequiredFieldValidator不激发如果文本框为空,我按TAB或究竟是什么触发RequiredFieldValidator
If RequiredFieldValidator is invalid why does AutoPostBack still occur,is not Validators checked before in page life cycle? 如果RequiredFieldValidator无效,为什么仍会发生AutoPostBack ,是否在页面生命周期中未检查Validators?

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace Registration_LoginPortel
{
public partial class RegistrationPage : System.Web.UI.Page
{
    int i = 0;
    protected void Page_Load(object sender, EventArgs e)
    {



    }
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        lblLoginAvailable.Visible = false;
        Response.Write("PPpostback" + (++i));
        if (!CheckLogin(Usn.Text.ToString().Trim()))
        {
            //Register the user
            try
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
                con.Open(); string s = Usn.Text;
                string sql_insertQuery = "INSERT INTO UserData(username,password,country)values (@UName,@UPass,@UCountry)";
                //string sql_insertQuery = "INSERT into UserData(username,password,country) VALUES ('"+Usn.Text+"','"+pass.Text+"','"+country.Text+"')";
                SqlCommand com = new SqlCommand(sql_insertQuery, con);
                com.Parameters.AddWithValue("@UName", Usn.Text);
                com.Parameters.AddWithValue("@UPass", pass.Text);
                com.Parameters.AddWithValue("@UCountry", country.Text);

                com.ExecuteNonQuery();
                // Response.Redirect("Admin.aspx");
                Response.Write("Registration is successfull");
                con.Close();
            }
            catch (Exception ex)
            {
                //Response.Write("Error : " + ex.Message);
                Response.Write("\n\nError : " + ex.ToString());
            }
        }
        else
        {
            lblLoginAvailable.Visible = true;
            lblLoginAvailable.Text = "This login already exists in our system. Chooce another login please";
        }
    }
    protected bool CheckLogin(string login)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select count(*) from UserData where lower(username) = lower(@login)", con);
        cmd.Parameters.Add("@login", SqlDbType.VarChar).Value = login;
        string id = "";
        try
        {
            con.Open();
            id = (int)cmd.ExecuteScalar() == 0 ? "" : cmd.ExecuteScalar().ToString();
        }
        catch (Exception ex)
        {
            //...
        }
        finally
        {
            con.Close();
        }
        if (String.IsNullOrEmpty(id)) return false;
        return true;
    }


    protected void Usn_TextChanged(object sender, EventArgs e)
    {
        lblLoginAvailable.Visible = false;

    }

}

} }

The page is posting back, so going back to the server and it's kind of fighting with your RequiredFieldValidator. 该页面正在回发,因此返回到服务器,这与您的RequiredFieldValidator格斗。 In the background your RequiredFieldValidator is passing Javascript to the page which is then doing its magic and checking to see if it needs to display a message. 在后台,您的RequiredFieldValidator将Javascript传递给页面,然后页面进行魔术操作并检查是否需要显示消息。 When a postback event is firing it's posting the whole page back and on it's return it's reloading the page thus losing the jscript message on the UI. 当发回事件触发时,它会将整个页面发回,并在返回时重新加载页面,从而丢失UI上的jscript消息。

I'd recommend not having the autopostback for something like this as it places unnecessary load onto the server. 我建议不要为此类事进行自动回发,因为这会给服务器带来不必要的负载。 What exactly do you want that event to do? 您到底希望该事件做什么?

you may just delete your requiredfieldvalidator, and your button's code will be: 您可以删除您的requiredfieldvalidator,然后按钮的代码将为:

<asp:Button ID="btnSubmit" runat="server" OnClientClick="return checkvalue();" OnClick="Button_Click" />

checkvalue() is an javascript method, using which you will check your textbox's value. checkvalue()是一种javascript方法,您将使用该方法检查文本框的值。

<script type="text/javascript">
    function checkvalue(){
        var txt = document.getElementById("yourTextboxId");
        if (txt.value.length == 0){
            alert('Insert a data');
            txt.focus();
            return false;
        }
        return true;
    }
</script>

This script will occur only when user will click on the button, it will not fire a postback. 仅当用户单击按钮时,此脚本才会出现,它不会触发回发。 This script will check length of text inside your textbox and, if length is 0 which means no text is inputted, will ask an user to input the text and cursor will be automatically set to your textbox control. 该脚本将检查文本框中的文本长度,如果长度为0(表示未输入文本),将要求用户输入文本,并且光标将自动设置为文本框控件。

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM