I am having following textbox in my aasp.net page. And user enters any username in it and I want ajax to check the availability and show the success or failure message in the label as the user leaves the text box.
UserName<asp:Label ID="usernamelbl" runat="server"></asp:Label>
<asp:TextBox ID ="usernametxt" runat="server" CssClass="twitterStyleTextbox"></asp:TextBox><br />
thats how I am using the ajax
function result() {
var username = "<%=usernametxt%>";
var result = "<%usernamelbl%>";// here i am getting an error on usernamelbl
var jsonText = JSON.stringify({ list: username });
//array = +jsonText;
$.ajax({
url: "staffregistration.aspx/Test", type: "POST", dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonText,
success: function (data) {
if (data == username) {
result = "username available"
}
else {
result = "username not avilable"
}},
error: function () { alert("its not working"); }
});
return false;
}
and thats how i am interacting with the aspx
public static string Test(string username)
{
string conString = #"user id=ejaz;password=ejaz;persistsecurityinfo=True;server=localhost;database=geospatialdb";
MySqlConnection conn = new MySqlConnection(conString);
MySqlDataReader reader = null;
conn.Open();
MySqlCommand command = new MySqlCommand("select owner_id from owner where owner_username = '" + usernametxt.Text + "';", conn);
reader = command.ExecuteReader();
username = reader[0].ToString();
return username;
}
Here is how you can detect the change in usernametxt using JavaScript through onChange event and Ajax using WebMethods.
ASPX Page: Make sure to set EnablePageMethods = true in the ScriptManager object.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="usernameupdatepanel">
<ContentTemplate>
UserName <asp:Label ID="usernamelbl" runat="server"></asp:Label>
<asp:TextBox ID ="usernametxt"
runat="server" CssClass="twitterStyleTextbox"
OnChange="CheckUserName(this)" ></asp:TextBox><br />
</ContentTemplate>
</asp:UpdatePanel>
JavaScript:
function CheckUserName(oName)
{
PageMethods.UserNameChecker(oName.value, OnSucceeded);
}
function OnSucceeded(result, userContext, methodName)
{
lbl = document.getElementById('<%=usernamelbl.ClientID %>');
if (methodName == "UserNameChecker")
{
if (result == true)
{
lbl.innerHTML = 'username not available';
lbl.style.color = "red";
}
else
{
lbl.innerHTML = 'username available';
lbl.style.color = "green";
}
}
}
C# Code-Behind: You can call a WebMethod to check if the new selected filename exists in the DB:
You need to reference the following:
using System.Web.Services;
Then add the following method and make sure you put [WebMethod] before method declaration:
[WebMethod]
public static bool UserNameChecker(string newUserName)
{
string conString = #"user id=ejaz;password=ejaz;persistsecurityinfo=True;server=localhost;database=geospatialdb";
MySqlConnection conn = new MySqlConnection(conString);
MySqlDataReader reader = null;
conn.Open();
MySqlCommand command = new MySqlCommand("select owner_id from owner where owner_username = '" + newUserName + "';", conn);
object found = command.ExecuteScalar();
if (found != null)
return true;
else
return false;
}
In a more simple way, just add the scriptmangaer tag and the update panel, then you add the textbox.
Note: Don't forget to set autopostback to true and add an event i.e OnTextChanged event and its handler
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="Email" OnTextChanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="" ></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The event handler
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//your logic
}
Related
Hello I did build a autocomplete text field for my project:
HTML Coding:
<!-- Autocomplete Function -->
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender" runat="server" CompletionSetCount="10" TargetControlID="input_source"
ServiceMethod="GetCompletionList" CompletionInterval="100" EnableCaching="false" MinimumPrefixLength="1">
</ajaxToolkit:AutoCompleteExtender>
<!--Inputfield Autocomplete-->
<asp:TextBox autocomplete="on" id="input_source" OnTextChanged="input_source_TextChanged" runat ="server" class="form-control" placeholder="Please enter"></asp:TextBox>
Code behind C#:
//Autocomplete Field
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCompletionList(string prefixText, int count)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = lr_sqlserver;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT TOP 5 Source FROM" + " " + selected_table + " " + "WHERE Source like '%' + #Search + '%'";
com.Parameters.AddWithValue("#Search", prefixText);
com.Connection = con;
con.Open();
List<string> suggestions = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
suggestions.Add(sdr["Source"].ToString());
}
}
con.Close();
return suggestions;
}
}
}
Now I want to call the following function everytime I select a suggestion from the autocomplete function. Is something like this possible?
protected void input_source_TextChanged(object sender, EventArgs e)
{
string source = input_source.Text;
using (
SqlConnection com = new SqlConnection())
{
//SQL Server
com.ConnectionString = lr_sqlserver;
//Conncection establish
com.Open();
//Get SQL Information
SqlCommand select = new SqlCommand("select target from " + selected_table + " where source = #param", com);
select.Parameters.AddWithValue("#param", source);
string result;
result = (string)select.ExecuteScalar();
if (result != null)
{
input_target.Text = result;
}
}
}
You would need to put your TextBox inside an UpdatePanel and on the TextBox set AutoPostBack="True"
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox autocomplete="on" id="input_source" OnTextChanged="input_source_TextChanged" runat ="server" class="form-control" placeholder="Please enter" AutoPostBack="True"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
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!";
}
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.
Based on the code you have, in Web Forms you can:
use an Update Panel;
or Page/Web Method
or a simple(r) Web handler (ashx)
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");
}
});
});
});
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.
how can i do a login with current user? the current user will be displayed in the masterpage of the default homepage and the label from the masterpage will inherit to the content pages of the master page.
here is my login page asp code:
<div class="container-fluid">
<form class="form-signin" runat="server">
<h1 class="form-signin-heading text-muted">Sign In</h1>
<asp:TextBox ID ="email" runat="server" CssClass="form-control" placeholder="Email Address"></asp:TextBox>
<asp:TextBox ID ="password" runat="server" CssClass="form-control" placeholder="Password" TextMode="Password"></asp:TextBox>
<br />
<asp:Button ID="btnLogIN" runat="server" CssClass="btn btn-primary btn-block" Text="Log In" OnClick="btnLogIN_Click" />
</form>
and my aspx.cs code is here and i dont know if this is correct.
protected void btnLogIN_Click(object sender, EventArgs e)
{
Utility u = new Utility();
string conn = u.connect();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand read = connUser.CreateCommand();
SqlDataReader reader = null;
int empid = 0;
string dbuser = "";
string dbpword = "";
string username = email.Text;
string passwords = password.Text;
string login = "Select * from MOSEFAccount where UserName = '" + username + "' AND Password = '" + passwords + "'";
try
{
connUser.Open();
read.CommandText = login;
reader = read.ExecuteReader();
}
catch
{
Console.WriteLine("Error");
}
while (reader.Read())
{
empid = reader.GetInt32(0);
dbuser = reader.GetString(1);
dbpword = reader.GetString(2);
}
if (username == dbuser && passwords == dbpword)
{
Response.Redirect("~/Default.aspx?ID=" + empid);
}
else
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type ='text/javascript'>");
sb.Append("alert('Invalid Account');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);
}
connUser.Close();
}
Can you elaborate on the meaning of current user? Unless you login you are not logged in user but anonymous user.
Update:
Store the pulled data in Session object and access it anytime whenever and wherever you like. For example:
For storing details use:-
if (username == dbuser && passwords == dbpword)
{
Session["UserName"] = username;
Session["EmpId"] = empid;
Response.Redirect("~/Default.aspx?ID=" + empid);
}
For displaying use (in the master page):
<%=Session["UserName"]%>
<%=Session["EmpId"]%>
You can build upon this like creating a User class and then creating an instance of this class and storing the instance itself in Session.
I have a link button as follow
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx" runat="server">Recherche </asp:LinkButton>
i want get a query string from it
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx?id=12" runat="server">Recherche </asp:LinkButton>
and the id value comes from the source code
public string ID
{
get { return ViewState["id"]; }
}
To get the value on page load (in the backend .cs file) :
protected void Page_Load(object sender, EventArgs e)
{
var id = Request.QueryString["id"];
if (id != null)
{
// use id
}
}
Or you might want to put the id into the link (in the html) :
<asp:LinkButton ID="LinkButtonSearchClient" runat="server"
NavigateUrl='<%# String.Format("~/UI/clients.aspx?id={0}", Eval("ID"))%>'
Text='Recherche'></asp:LinkButton>
You probably do not need a postback, look here : PostbackUrl vs NavigateUrl
Try this,
public string ID
{
get { Request.QueryString["id"]; }
}
Edit : In your page load set your postback url like this, access postbackurl in server side
LinkButtonSearchClient.PostBackUrl = "~/UI/clients.aspx?id=" + this.ID;
See my following example :
in design as follow
<asp:HyperLink ID="HLink" runat="server"
NavigateUrl='<%#"Mobiles_Details.aspx?ID=" + Eval("ID") %>' Text='<%#
Bind("Name") %>' Height="70px" Width="200px" Font-Bold="true" Font-
Size="10pt" Font-Names="Times New Roman" />
In coding the class Mobiles_Details is:
public partial class Mobiles_Details : System.Web.UI.Page
{
public string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
Session["UserID"] = "100";
//int ID = 102;
int ID = Convert.ToInt32(Request.QueryString["ID"].ToString());
Session["Product_ID"] = ID;
if (Session["UserID"] == null || Session["UserID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx", false);
}
else
{
if (ID != null)
{
DataTable dt = Load_Items_ID(Convert.ToInt32(Session["UserID"].ToString()), ID);
lbl_Name.Text = dt.Rows[0]["Name"].ToString();
lbl_Price.Text = dt.Rows[0]["Price"].ToString();
lbl_Details.Text = dt.Rows[0]["Details"].ToString();
img_Product.ImageUrl = dt.Rows[0]["image"].ToString();
}
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('An Error has been occured ');" + ex.ToString(), true);
}
}
}
public DataTable Load_Items_ID(int UserID, int ID)
{
DataTable Returned_Value = new DataTable();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Products where UserID= " + UserID + " and Status='False' and ID =" + ID))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(Returned_Value);
}
}
}
}
return Returned_Value;
}
}
I wants to retrieve data from sql server using webserver/jquery and I read many articles but not getting the require matters except below but I think It's support FrameWork .Net 3.5 not 2.0. And I have the same requirement to use it in ASP.Net 2.0.
//On WebServer Page..
WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class test : System.Web.Services.WebService
{
[WebMethod]
public string GetCustomer(string memberID)
{
string response = "<p>No customer selected</p>";
string connect = "Server=myserver;Initial Catalog=mydatabase;uid=myuser;pwd=mypassword";
string query = "SELECT name, father, mother from samaj where name=#memberID";
if (memberID != null)
{
StringBuilder sb = new StringBuilder();
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("memberID", memberID);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
sb.Append("<p>");
sb.Append("<strong>" + rdr["name"].ToString() + "</strong><br />");
sb.Append(rdr["father"].ToString() + "<br />");
sb.Append(rdr["mother"].ToString() + "<br />");
response = sb.ToString();
}
}
}
}
}
return response;
}
}
}
//.aspx page...
<script type="text/javascript" src="jquery-1.3.2.min.js" ></script>
<script type="text/javascript" >
$(document).ready(function(){
$("#Customers").change(function()
{
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "test.asmx/GetCustomer",
data: "{ memberID: '" + $('#Customers').val() + "'}",
dataType: "json",
success: function(data)
{
$("#CustomerDetails").html(data.d);
}
});
});
});
</script>
<form id="form1" runat="server">
<div id="SelectCustomers">
<asp:DropDownList ID="Customers" runat="server">
</asp:DropDownList>
</div>
<div id="CustomerDetails">
</div>
</form>
The DropdownList Binding In Default.aspx.cs page...
protected void Page_Load(object sender, EventArgs e)
{
string connect = "Server=myserver;Initial Catalog=mydatabse;uid=myuser;pwd=mypwd
string query = "SELECT name FROM samaj";
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
Customers.DataSource = cmd.ExecuteReader();
Customers.DataValueField = "name";
Customers.DataBind();
}
}
.asmx page testing ok It’s retrieves the data well but on client side It’s not return any data. How to achieve it in ASP.Net 2.0?.