简体   繁体   中英

Get data from database without refreshing the page in ASP.NET

I'm doing a project in ASP.net and with SQL Server. I'm calling a stored procedure on user login screen to authenticate the user. But when I call the stored procedure, the entire page needs to be refreshed in order to get the data.

How can I achieve the same without refreshing the page?

This is my current code

sql = "EXEC dbo.sProc_Admin_Auth @UserNm = '" + User + "',@Pwd = '"+Pwd+"'";

cmd = new SqlCommand(sql, cn.connect());

dr = cmd.ExecuteReader();

if(dr.Read())
{
    Session["UserId"] = dr["UserId"].ToString();
    Session["LoginId"] = User;
    Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
    Session["Email"] = dr["Email"].ToString();
    Session["JoinDt"] = dr["CreateDt"].ToString();

    Response.Redirect("Index.aspx");
    LblError.Visible = false;
}
else
{
    LblError.Visible = true;
    LblError.Text = "Login Failed!";
}

If you want to load the data without refreshing the page. you can expose webservice method or create page method then you can call ASP.NET page method through ajax

[WebMethod]
public static string Insert_Data(string user, string pwd)
{   
            sql = "EXEC dbo.sProc_Admin_Auth @UserNm = '" + User + "',@Pwd = '"+Pwd+"'";

            cmd = new SqlCommand(sql, cn.connect());

            dr = cmd.ExecuteReader();

            if(dr.Read())
            {
                Session["UserId"] = dr["UserId"].ToString();
                Session["LoginId"] = User;
                Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
                Session["Email"] = dr["Email"].ToString();
                Session["JoinDt"] = dr["CreateDt"].ToString();
                Response.Redirect("Index.aspx");
                LblError.Visible = false;
            }
            else
            {
                LblError.Visible = true;
                LblError.Text = "Login Failed!";
            }

}

Client Side

 $(document).ready(function () {

            $('#btnsubmit').click(function () { 
               var name = $('#user').val();


                var sex = $('#pwd').val();

                $.ajax({

                    type: 'POST',

                    contentType: "application/json; charset=utf-8",

                    url: 'Default.aspx/Insert_Data',

                    data: "{'user':'" + user+ "','pwd':'" + pwd + "'}",

                    async: false,

                    success: function (response) {

                        alert("Record saved successfully..!!");

                    },

                    error: function () {

                        alert("Error");

                    }

                });

            });

        });

Based on the code you have, in Web Forms you can:

Use Ajax Extension , Here is the quick example:

.aspx File

    <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:TextBox runat="server" id="username" name="username" placeholder="Enter Username"></asp:TextBox>
            <asp:TextBox name="passwd" ID="passwd" runat="server" placeholder="Enter Password"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click" />
            <br />
            <asp:Label ID="LblError" runat="server"></asp:Label>
        </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

aspx.cs File - add this to Click event of Login Button

 protected void Button1_Click(object sender, EventArgs e)
        {
            string sql = "";
            SqlConnection cn = null;
            SqlCommand cmd = null;
            SqlDataReader dr = null;
            string User = username.Text;
            string Pwd = passwd.Text;
            //cn = "<< your connection string>>";
            try
            {
                cn.Open();
                // Your code

                sql = "EXEC dbo.sProc_Admin_Auth @UserNm = '" + User + "',@Pwd = '" + Pwd + "'";

                cmd = new SqlCommand(sql, cn);

                dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    Session["UserId"] = dr["UserId"].ToString();
                    Session["LoginId"] = User;
                    Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
                    Session["Email"] = dr["Email"].ToString();
                    Session["JoinDt"] = dr["CreateDt"].ToString();
                    Response.Redirect("Index.aspx");
                    LblError.Visible = false;
                }
                else
                {
                    LblError.Visible = true;
                    LblError.Text = "Login Failed!";
                }
            }
            catch (Exception exce)
            {
                LblError.Text = exce.Message;
            }
            finally
            {
                cn.Close();
            }
        }

You can find UpdatePanel and ScriptManager under Toolbox -> Ajax Extension


Use try-catch block to handle runtime exceptions.

There are 3 possible ways I know of:

1) using update panel:
see example: http://www.aspdotnet-pools.com/2014/07/ajax-login-form-in-aspnet-using-cnet.html

2) using webmethod:
see example: http://www.aspforums.net/Threads/133296/Develop-simple-AJAX-Login-form-using-jQuery-in-ASPNet/

3) using tiered coding:
see example: https://www.codeproject.com/Articles/170882/jQuery-AJAX-and-HttpHandlers-in-ASP-NET

I prefer method 3 coding as it is more flexible and the tiered coding concept is portable to other web programming platform.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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